Flash CS4 Planetarium in 49 Lines

April 22, 2009

Intro

In Chapter 7 of the book I change the  Planetarium example (shown in a previous post) so that it only uses XML (threw out Cairngorm). And in the process I thought, hey this should be easy to do in CS4. And it was! Check it out below…a planetarium (with real star data) in 49 lines of code…including comments.

Flash CS4 Planetarium in 49 Lines

Flash CS4 Planetarium in 49 Lines

Demo

Source

Disucssion

There are two main steps in getting this to go:

Step 1: Get a star object into your library so you can instantiate it onto the stage like you would your particles class – this step saves you tons of code: var myStar = new Star();

Star in the Library for Instantiation

Star in the Library for Instantiation

Step 2: Treat your stars like a particle system. This lets your stuff then into an updatable array so you can rotate them:

The rest of this stuff you’ve seen before, and I go through the discussion in the book and in the YouTube video above so I just show the code below: myParticles[j]

Sample Star Data (CSV)

AND, 2.065, 42.316, 0,
AND, 1.161, 35.616, 1,
AND, 0.655, 30.85, 1,
AND, 0.139, 29.083, 1,

CS4 Planetarium in 49 lines

import flash.events.*;
import flash.display.*;

//Create star parameters
var myStar:Star;
var skyRadius:Number = 240;
var myOsc:int=0;
var starHolder:MovieClip= new MovieClip();

//Create a star array to hold CSVdata and particle array
var starArray:Array=new Array();
var myParticles = new Array();

//XML Statements used to bring in XML data
var urlRequest:URLRequest = new URLRequest(“data/starData.xml”);
var xmlLoader:URLLoader = new URLLoader(urlRequest);
xmlLoader.addEventListener(“complete”, readXml);

//XML parser and CSV splitter
function readXml(event:Event):void{
var markersXML:XML = new XML(event.target.data);
starArray=markersXML.myStars.split(“,”);

//Set the initial star system in place and add to a Movie holder
for(var i:uint = 0; i < starArray.length/4; i++){

//Instantiate stars and place them in a particle array
var myStar = new Star();
myParticles.push(myStar);
starHolder.addChild(myStar);

//Position stars (x, y, z) on stage
myStar.x=skyRadius*(Math.cos(2*Math.PI*starArray[4*i+1]/24)*Math.sin((90-starArray[4*i+2])*Math.PI/180));
myStar.z=-skyRadius*(Math.sin(2*Math.PI*starArray[4*i+1]/24)*Math.sin((90-starArray[4*i+2])*Math.PI/180));
myStar.y=skyRadius*Math.cos((90-starArray[4*i+2])*Math.PI/180);

//Scale stars according to magnitude and give a rand rotation
myStar.scaleX=myStar.scaleY=(1/9)*(3-starArray[(4*i+3)]);
myStar.rotation=180*Math.random();
}

//Add stars to star holder and position the holder
addChild(starHolder);
starHolder.x=400;
starHolder.y=300;

//Create your animation loop using an Enter Frame Listener
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

function onEnterFrame(event:Event):void{
//Increment oscillation parameter and iterate over stars
myOsc++;
for(var j:uint = 0; j < starArray.length/4; j++){

//Set new x, y, z for your stars as they rotate
myParticles[j].x=skyRadius*(Math.cos(2*Math.PI*starArray[4*j+1]/24+myOsc/180)*Math.sin((90-starArray[4*j+2])*Math.PI/180));
myParticles[j].z=-skyRadius*(Math.sin(2*Math.PI*starArray[4*j+1]/24+myOsc/180)*Math.sin((90-starArray[4*j+2])*Math.PI/180));
myParticles[j].y=skyRadius*Math.cos((90-starArray[4*j+2])*Math.PI/180);
}}


Flash CS4 Exploding House of Cards (3D Particle Class)

April 15, 2009

Intro

Exploding an object is serious gaming fun. There’s just something about the human psyche that loves to see things blow up. In this post, we show you how to create a card house in Flash CS4 and then how to blow it up by treating the cards as particles.

Exploding House of Cards

Exploding House of Cards

Demo

Source: http://flex3cookbook3.googlecode.com/files/blowitUp3D.zip


YouTube Video 1: Building a House of Cards in CS4 (Part 1)

YouTube Video 2: Building a House of Cards in CS4 (Part 2)

YouTube Video 3: Making Your CS4 Card House Explode (Part 3)

Discussion

The first step in making things explode is to add a spin (x, y, z) property to your Particle3D class (developed in the book).

You can accomplish this in the following three steps:

Exploding an object is serious gaming fun. There’s just something about the human psyche that loves to see things blow up. The first step in making things explode is to add a spin (x, y, z) property to your Particle3D class. You can accomplish this in the following three steps:

Step 1: To keep things straight rename your Particle3D (developed in the book) class to ParticleBlowUp and add a spin (x, y, z) property

public var spinX:Number;
public var spinY:Number;
public var spinZ:Number;

Step 2: In the constructor function, set the spin (x, y, z) equal to zero.

spinX = 0;
spinY = 0;
spinZ = 0;

Step 3: And in your animation method “myLoop” update the rotation of the particle by iterating the spin (x, y, z) amount.

this.rotationX += spinX;
this.rotationY += spinY;
this.rotationZ += spinZ;

And that’s all you have to do to your Particle3D (now named ParticleBlowUp) class. See the book for more details…

You’re Only Half Way

But to get your particle system to explode you want to transfer a multi-part movie clip into your Particle class (using polymorphism). Then iterate over the elements of that movie clip, so you can spin those elements off into space in different directions, simulating an explosion.

To do this, make the following changes to your Particle3D class shown below:

1. Remove the “extends Sprite” statement from your ParticleBlowUp class; this allows you to bring in an object into your ParticleBlowUp class.

2. Create a public property “obj” and data type it as a Display Object:

public var obj:DisplayObject

3. Add “obj” to your constructor method, declare “obj” as an object in your constructor method.
4. Finally, change all the “this” keywords to object so that the transformations are applied to the object passed in through the constructor.

To see the rest of the discussion click the link below:

Read the rest of this entry »


Animating Multiple Pixel Bender Lights

March 21, 2009

Intro
Having multiple lights in PV3D is a desired effect. But after going through the lightmap classes, let me say that it’s impossible without an major rewrite. But with Pixel Bender all you do is add another term to your pbk filter…let’s do it!

Animating Pixel Bender Lights

Animating Pixel Bender Lights

Demo

Source

Discussion

It’s an amazingly simple process. Just add another term to your pixel bender light equation as shown below:

Adding Multiple Images to PV3D

Adding Multiple Images to PV3D

The example above only shows two lights, but you can have as many lights as you want just by adding additional light terms:

The pixel bender code looks like this

float2 outcoord = outCoord();
float attn = (brightness1/((distance(outcoord, center1)+radius1)))+(brightness2/((distance(outcoord, center2)+radius2)));

dst = attn* sampleNearest(src, outcoord);
dst.a=1.0;

Wow, only five lines of code to have multiple light sources – get out of here!

Animating Your Sources

Once you’ve set your shader up then animating it is pretty easy. If you aren’t sure how to set up your shader for animation, check out Lee Brimlow’s video on animating shaders. I do it a little differently than Lee, but not by much. Here are the steps for animating the lights:

  1. Increment your oscillation parameter osc++
  2. Calculate sine and cosine based upon your incremented osc
  3. Update your light positions
  4. Apply the update to your image

The fully documented code is shown below:

private function loop(e:Event):void{

//Increment your oscillation parameter
osc++;
//Calculate sine and cosine
var cos:Number=150*Math.cos(osc/10);
var sin:Number=150*Math.sin(osc/10);
//Update your light positions
shader.data.center1.value = [sin+400, cos+180];
shader.data.center2.value = [cos+200, sin+180];
//Apply the update to your image
image.filters = [filter];
//Rotating your image holder
holder.rotationY+=.25;
}

If you are aware of how hard this is to do in PV3D, you’re going wow…tell me more…and we will…

For the entire source code download the source above, or check out the link below:

Read the rest of this entry »


Adding Pixel Bender to Papervision3D

March 20, 2009

Intro

One of the things which I abhor about modeling in Papervision3D is texture baking. And if you’ve been in the business as long as I have you know why…it’s a labor intensive nightmare…and you can’t ever get it right. But with pixel bender you don’t have to bake your textures anymore and you can adjust your parameters dynamically using ActionScript.

Dynamic Shading using Pixel Bender

Dynamic Shading using Pixel Bender

Demo

Source

YouTube http://www.youtube.com/watch?v=i8BnSqf0Z_g

Discussion

Adding Pixel Bender to Papervision3D was a three step process:

  • Creation of a Pixel Bender Filter
  • Creation of a Pixel Bender Bitmap File Material Class
  • Creation of a Pixel Bender Bitmap Material Class
Adding Pixel Bender to PV3D

Adding Pixel Bender to PV3D

Before you start coding. Make sure you’ve switched to the Flash 10 player!!!

Step 1: In the previous post several pixel builder filters were presented.

Pixel Bender Filters and Algorithms

To create a dynamic light baker filter the simple light filter was modified by throwing out all the pow and exponent methods. The big trick is that exponential behavior can be mimicked by using inverse of distance –now that’s a processor saver. The final algorithm use is shown below:

lively3d Light Source for Texture Baking

lively3d Light Source for Texture Baking

The pixel bender algorithm is easily implemented using the code below:

float2 outcoord = outCoord();
float attn = (brightness/((distance(outcoord, center)+radius)));

dst = attn* sampleNearest(src, outcoord);
dst.a=1.0

In addition to the modification mentioned above the alpha component is split off and set to one. This keeps the images from losing its alpha as you reduce brightness.

Step 2: Next you must create a Pixel Bender Bitmap File Material Class. This is simply done by making a copy of PV3D’s BitmapFileMaterial class and renaming it BitmapBendMaterial class and after changing the constructor and class names extend this class by the BitmapPixelMaterial class.

BitmapBendMaterial extends BitmapPixelMaterial

You’ll now create the BitmapPixelMaterial class.

Step 3: Make a copy of the PV3D BitmapMaterial class and name it BitmapPixelMaterial. Add the appropriate import statements and the pbj and image embed methods and create a shader as shown below:

[Embed (source="filters/livelyLight.pbj",
mimeType="application/octet-stream")]
private var ShaderClass:Class;

[Embed (source="assets/images/gainesHouse512.jpg")]
private var myImage:Class;

private var shader:Shader

Next incorporate the code to get your shader and image working together:

shader = new Shader(new ShaderClass());
shader.data.center.value = [400, 306];
shader.data.brightness.value = [150];
shader.data.radius.value = [100];

var image:Bitmap = new myImage();
image.filters = [new ShaderFilter(shader)];
shader.data.src.input = image.bitmapData

Finally you must change your fill method to a shader fill method with a matrix method

graphics.beginShaderFill(shader,_localMatrix)

That’s it! To check out the wrapper code download the source or click the more button below:

Read the rest of this entry »


Flex 4 (Gumbo) Fire Video on the Supper Club

March 13, 2009

Intro

Our group just finished the first part of the Beverly Hills Supper Club project. I realize that this is a sensitive area and lives were lost. The completed site will be a memorial to those loved ones that were lost in this tragic fire.

Here I demonstrated playing the Supper Club fire video on the Blender building skin. To see the demo just click the image below (drag the building with the mouse to rotate it and click the play video button to get the video to play):

Supper Club Video on a Blender Model

Supper Club Video on a Blender Model

Demo

Code (Only MXML File – Video too large for Google Code)

UTube

Discussion

It’s pretty easy. Just follow the posts below which explain everything in detail:

1. Learn about netStream and netConnection

Adding Video to a Papervision3D Curved Plan

2. Learn about using video in CS4

Putting Video on a CS4 (Flash 10) Primitive

3. Learn how to build a CS4 shaded model using drawTriangles

CS4 Flat Shaded Tie Fighter with drawTriangles

4. Learn about Light in Papervision3D

Adding Brightness to PV3D Light Source

5. Learn how to model in Blender

3D Modeling

6. Learn how to export your Blender models to Papervision3D and CS4

New Blender XML Exporter/PV3D XML Primitive

The big trick to this is to create a simple parameter that allows you to switch between the shaded model and video within the triangle creation loop.

playMyVideo = false or true;

Run Shade Code if false

….

Run Video Code if true

}else{

var vertices2:Vector.<Number>=new Vector.<Number>();
vertices2.push(dispVec[facesVec[curFace][0]].x, dispVec[facesVec[curFace][0]].y);
vertices2.push(dispVec[facesVec[curFace][1]].x, dispVec[facesVec[curFace][1]].y);
vertices2.push(dispVec[facesVec[curFace][2]].x, dispVec[facesVec[curFace][2]].y);

//Draw Video into Bitmap
bitmapData.draw( this.myVideo);
this.myVideo.attachNetStream ( this.myStream );

spObjImage.graphics.beginBitmapFill(bitmapData,null, false, false);
spObjImage.graphics.drawTriangles(vertices2);
spObjImage.graphics.drawTriangles(vertices2)

}

Another trick is handling rotations correctly. To do this you need to use subtraction of your previous position from you present position (since you are appending rotation in this example). So if you are rotating forward the difference is positive and if backwards the difference is negative.

private function boardMove(e:MouseEvent):void {

var locX:Number=prevX;
var locY:Number=prevY;
if(doRotate){
prevX=spBoard.mouseX;
prevY=spBoard.mouseY;
rotateObj(prevY-locY,-(prevX-locX),0);
e.updateAfterEvent();

}

Once you “get this in your head” you’ll undertstand “append” rotation in CS4 – otherwise it’s uncontrollably wild.

Now there’s on more “Super trick”. This application was originally created for an Adobe Air and was run on the desktop. So when you put it on the web the video will not work since it uses

spObjImage.graphics.drawTriangles(vertices2)

looks like a terrible sandbox issue, but wait a second didn’t we get video on a prim in the previous post on Putting Video on a CS4 (Flash 10) Primitive…

Yes we did???

But this time we don’t have indices and uv data … shouldn’t we just give up or get some expert to tell us what to do…nah, just replace indices and uv data with null and it works…please don’t ask me why. Remember, I said this was a trick.

spObjImage.graphics.drawTriangles(vertices2, null, null,TriangleCulling.NEGATIVE);

And Tada, video on the Supper Club.

Remarks

The full project will allow site visitors to leave messages in supper club rooms…building a flexpress flat-file data base to handle these messages is part of the TEI project… The advantage of the flat-file data base is that you can drop the program onto any server – hassle free and it works – no fancy install!

To see the entire code click the more button below:

Read the rest of this entry »


Putting Video on a CS4 (Flash 10) Primitive

March 10, 2009

Intro

Get ready to eliminate 1000′s of lines of Papervision3D code. That’s right! By using CS4 you no longer need the Movie Material class, the DisplayObject3D class, the Video Stream Material class, and a plethora of Triangle/UV parsing and math classes. It’s just amazing…in CS4 it’s so simple!

Video on a CS4 Primitive

Video on a CS4 Primitive

Demo

Source

YouTube


Discussion

Note: This discussion uses the code and results of two previous posts:

Adding Video to a Papervision3D Curved Plane

CS4 Super Primitive using Matrix3D

Placing video on the CS4 Super Prim developed in Chapter 3 of the book is very easy and only requires four steps.

  • Step 1: Import the net and media classes in to the Super Prim Class (see the post on CS4 Super Primitive using Matrix3D – this is your starter code)
  • Step 2: Declare the video, net Connection, and net Stream variables.

//net stream assets
private var myConnection : NetConnection;
private var myStream : NetStream;
private var myVideo : Video;

  • Step 3: Incorporate the loadMyVideo() method discussed in the previous post on Adding Video to a Papervision3D Curved Plane
  • Step 4: Create a bitmapData object and in the animation loop draw your video to that bitmapData object and attach the net stream to your video, as shown below:

//Draw Video into Bitmap
bitmapData.draw( this.myVideo);
this.myVideo.attachNetStream ( this.myStream );

The results yield a video being played among the various prims contained in the super prim. At this point you change the video by changing the file name inside your net Stream method (myStream.play(“assets/eternity.flv”)), but the constructor function could be easily changed to receive a video string locater.

A Little Extra

Also in Chapter 4 of the book, we show you how to put your webcam video on a prim. Below is a shot of my Guinea Pig Don Pedro who jumped into the screen to get his web cam video on a sphere.

Pig on a WebCam

Pig on a Web Cam

The code for this is included in the download above. But the explanation is in the book. To see the entire code download the source from the link above, or click the more button below:

Read the rest of this entry »


CS4 Google Maps Project – a money maker!

March 8, 2009

Intro

It seems like most sites like mine give you basic examples of how to do things but never take you to the next level – the level that makes money. This project, though not complete, closed the deal on a contract and is great starter code for any one doing Google maps.

It ‘s an air project, and the code is a little disorganized due to the short time frame. Basically, I had written the same project in Papervision3D but my buttons were off, but in CS4 everything is right on. So in about four hours I transferred this project from Papervision3D to CS4.

Code was flying everywhere and by the end of it I had to spray my keyboard down with liquid nitrogen … it was smok’n red hot …

The contract crew walked into the meeting with a good working prototype, where others were not even close, and guess what … they got funded … and that’s the way to do it. Give your clients something that works (a few bells and whistles) … not just a design … and you’ll win every time (unless the other contractor is the boss’s brother – it happens.).

Landmark Covington

Landmark Covington Air Project

The original Papervision3D code was Wii controlled and I left the Wii code inside the project just in case I needed to reactivate it. Check out my Wii Post to learn how to create a Wii controlled project.

Source 200+ Megs

YouTube

Discussion

Here are the highlights of its development.

1. Use of Flex custom mxml components and Cairngorm to control pop-ups with images and audio

Flex Popup Component

Flex Popup Component

2. removedFromStage trick to close audio after clicking the close button of the maps pop up (same component can be used for video pop-ups as well).

MXML

<mx:Canvas xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; width=”482″ height=”222″ creationComplete=”MyImageBox()” removedFromStage=”leaveStage()” horizontalScrollPolicy=”off” verticalScrollPolicy=”off” fontSize=”12″ backgroundColor=”#FFFFFF” alpha=”1.0″ backgroundAlpha=”0.0″>

ActionScript

private function leaveStage():void{

if(soundChannel){

soundChannel.stop();

SoundBtn.label=”Play Audio”;

}}

3. Primitive swapping using remove and add child

//movieParent.
movieParent.removeChildAt(0);
movieParent.addChild(tunnel);

4. Location navigation using a Combo Box including animated map directions

Navigation Menu

Navigation Menu

5. Application.application.map trick to add Google Maps to Flex

movie.addChild(Application.application.map);

Map in 3D

Map in 3D

6. XML data file to hold pop-up info including audio location.

XML for Marker Pop-up Box

XML for Marker Pop-up Box

I could spend 1 week going through every detail, but the stuff above was the stuff I had to think about! Hope it helps…

Sorry about the messiness of the code. Like I said, it was pretty short order. Once the project was completed, I didn’t have time to rework it. But if you’re working on a project like this one…this code will be very helpful to you. The real key to making this thing work was creating custom Flex components and using Cairngorm to talk to them. Google maps pops them up, and you can put anything in them: audio, video, or 3D.

I’m off to the next job. This coming week one of my programs is being presented in Austria (I haven’t written it yet…of course). But my graphic designers have been working like crazy building the assets for it.

I write about 5000 “working” lines of code a week now (that’s about two projects a day)…but that’s because my code base is growing. The more code I have, the more I can write…that’s right…this number includes cutting and pasting code from one project to another.

Once the Austria project is completed, I’ll post it so you can see how these larger (money making) projects go. Have a great week…


Plotting Equations in 3D – NKU Sem#5 (Links)

March 3, 2009

Plotting in 3D using Papervision3D and CS4.

Seminar #5

Here’s the class links for Plotting Equations in 3D: a free public seminar at NKU.

If you’re an educator or student get Adobe Flex for free at:

http://www.adobe.com/devnet/edu/

A. Resources: Flash & Math (Present Resources)
http://mathdl.maa.org/mathDL/3/?pa=content&sa=viewDocument&nodeId=1598&bodyId=1711

1. Parametric Surfaces in Rectangular Coordinates
2. Parametric Surfaces in Cylindrical Coordinates
3. Parametric Surfaces in Spherical Coordinates
4. Graphing Functions of Two Variables
5. Graphing Functions of Two Variables

B. Flash & Math (Barbara Kaskosz & Doug Ensley)

http://www.flashandmath.com (their book site)

Contour and 3D combined
http://www.flashandmath.com/advanced/contours/index.html

Implicit Plotter
http://www.flashandmath.com/intermediate/implicit/index.html

Simple Graph
http://www.flashandmath.com/basic/simplegraph/index.html

C. How Plotting in 3D is done in Flash
http://www.professionalpapervision.wordpress.com (my book site)

Flash 3D
http://professionalpapervision.wordpress.com/2008/12/11/building-a-3d-flash-engine-in-19-lines-of-code/

Flash & Math (how far can you go)
http://www.flashandmath.com/flashcs4/cs4simple3d/icosa.html

Not to be out done!
http://professionalpapervision.wordpress.com/2009/03/01/cs4-flat-shaded-tie-fighter-drawtriangles/

Note: 2D curves are created by connecting straight lines.

D. Plots in Papervision3D and CS4

Straight lines CS4
http://www.professionalpapervision.com/demos/web/lines3dcs4/

Curves in Papervision3D (straight lines pieced together)
http://www.professionalpapervision.com/demos/web/pendulum/FoucaultPend.html

Molecules
http://professionalpapervision.wordpress.com/2009/02/24/cs4-gumbo-molfile-molecule-viewer-sem4/

Particle Systems

Example 1 low number physics
http://professionalpapervision.wordpress.com/2008/11/21/real-orbiting-3d-particles-taking-out-the-trash/

Example 2 high number – billboarding physics
http://professionalpapervision.wordpress.com/2008/11/02/trilogic-particle-billboarding-flash-source/

Example 3 CS4 Particles
http://professionalpapervision.wordpress.com/2009/01/11/cs4-creating-a-parametric-particle-field/

E. Using the Geometry Trick (Papervision3D

Making Water (Exey Pantelee’s Blog)
http://exey.ru/blog/home/fluid-simulation-pv3d-and-away3d

objectName.geometry.vertices[i].x, y, or z

Sinc Function
http://www.nkuflc.org/sincplot

YouTube:

http://www.youtube.com/watch?v=YlFLT9YA44

Rubrics Cube
http://professionalpapervision.wordpress.com/2008/12/31/setting-up-a-rubiks-cube-in-papevision/

for(var i:int = 0; i<cubeGrid.geometry.vertices.length; i++)
{
var myPart:Cube = new Cube(materialArray[i], mySize/2.1,mySize/2.1,mySize/2.1,2,2,2);

myPart.x=cubeGrid.geometry.vertices[i].x;
myPart.y=cubeGrid.geometry.vertices[i].y;
myPart.z=cubeGrid.geometry.vertices[i].z;

particleArray.push(myPart);
myGraphicsHolder.addChild(myPart);
}

F. Parsing – in just 1900 lines of code???
You’ve got to be kidding me – click the more button below to see the code.

G. Where we are going! (3D Plotting Calculator Style)
Bring down the parser to 300 lines…maintainability vs. user experience. Move to IPhone.

Read the rest of this entry »


3D Lines in CS4 using drawPath

February 19, 2009

Intro

In the previous post on Pendulums, Papervision’s line3D class was used to plot the orbit of a Foucault Pendulum in a rotated plane. But there was a problem – adding more line segments slowed the processor and as result line segments had to be removed. Aha! You just thought I had created some really cool effect by erasing the end of my line while making the front. No, without erasing, everything would eventually slow down to a stand still.

Let’s speed things up a little by using CS4′s drawPath method. Click on the image below to see the demo.

3D Lines in CS4

3D Lines in CS4

Source

Demo

YouTube


Discussion: Drawing Points and Lines

Keith Peters in his book does a similar example using CS3 line functions, but he doesn’t sort his filled circles. His circles are black, and when you run his demo it appears as if the application is z-sorting-but it isn’t. If you try to applying his zSort algorithm the connecting lines go hay-wire. They don’t know where to go and try to follow his black circles as they rapidly sort.

Here’s the Trick

Commonly when we run into such issues in Papervision3D we create dummy graphics for our wayward objects to follow. So in this case you create dummy graphics under your circles for your lines to follow. Thus, separating the zSortng of the circles from the positions of your lines.

There ‘s a little bit of double processing here, but it’s worth it. And it’s very typical of solving problems of this type. In the code below, you see the parallel creation of the circle (or ball) and the dummy marker (or mark).

var ball:BallCS4 = new BallCS4(10, 0);
var mark:MarkCS4 = new MarkCS4(0, 0);
marks.push(ball);
balls.push(ball);
mark.xpos = ball.xpos = Math.random() * 200 – 100;
mark.ypos = ball.ypos = Math.random() * 200 – 100;
mark.zpos = ball.zpos = Math.random() * 200 – 100;
myHolder.addChild(ball);
myHolder.addChild(mark);

The MarkCS4 class is your dummy marker and is an object of zero pixel size – how do like that one! The BallCS4 class is similar to the MarkCS4 class. But draws a circle instead of a zero pixel line.

BallCS4 uses the drawPath method to create its circle in CS4. Since there are no drawCircles methods in CS4 you have to create one. I used four radial curves (created by the CURVE_TO method), which looks fine for small circles, but you’ll need to add eight for larger circles. The radius parameter (below) determines the size of your filled circle.

commands.push(GraphicsPathCommand.MOVE_TO);
data.push(-radius/1.9, radius/1.9);

data.push(0, radius);
data.push(radius/1.9, radius/1.9);

data.push(radius, 0);
data.push(radius/1.9, -radius/1.9);

data.push(0, -radius);
data.push(-radius/1.9, -radius/1.9);

data.push(-radius, 0);
data.push(-radius/1.9, radius/1.9);

commands.push(GraphicsPathCommand.CURVE_TO);
commands.push(GraphicsPathCommand.CURVE_TO);
commands.push(GraphicsPathCommand.CURVE_TO);
commands.push(GraphicsPathCommand.CURVE_TO);

graphics.lineStyle(0);
graphics.beginFill(0×800000);
graphics.drawPath(commands, data);

Extra Reading

A great article which explains this in more detail can be found on Senocular’s blog. Once you’ve got your “commands” and “data” Vectors loaded, you throw them into the drawPath function…and TaDah – sphere (or in this case filled circle)! Instantiate it as many times as you want.

zSort

Now that you’ve decoupled the spheres from the lines using the marker graphics you can now use Keith’s zSort method.

private function sortZ():void
{
balls.sortOn(“zpos”, Array.NUMERIC | Array.DESCENDING );
for(var i:uint = 0; i < numBalls; i++)
{
var ball:BallCS4 = balls[i];
myHolder.addChild(ball as Sprite);
}
}

The Big Limitation

The big limitation is that drawPath only draws in x and y – hey where’s the z Adobe? So to get around that limitation you have to use perspective scaling given in the code below:

var scale:Number = fl / (fl + ball.zpos);
ball.scaleX = ball.scaleY = scale;
ball.x = ball.xpos*scale;
ball.y = ball.ypos*scale;

That’s it, you’re ready to start using 3D lines in CS4. In an upcoming post, we will treat Creating 3D Springs and Making a Node Garden. And my favorite, 3D spring data visualization which I can’t wait to release. I’ve been working on this one for a while.

To see the entire code download the source above or click on the more button below.

Read the rest of this entry »


CS4 Animated Shuttle – drawTriangles Blender Parser

January 28, 2009

Intro

There’s been a number of posts speculating whether 3D models could be brought into CS4. The problem has do with properly mapping uv coordinates to the appropriate vertex values. In this post, I’ll demonstrate the development of a very simple parser which allows you to bring Blender models into CS4. It uses the drawTriangles method, the Blender XML Exporter created in a previous post, and a one-to-one mapping scheme of vertex and uv data points.

I’m sure that as time progresses more advanced parsers will be developed, but for our present projects, this one works really well.

Animated Shuttle

Animated Shuttle

Demo

Source

YouTube

Discussion

To create a Blender parser using the drawTriangles method, you’ve got to get your mapping right. It must be one-to-one: each vertex must have one unique uv point. But in modeling software, such as Blender, that’s not true. You can have multiple uv points for one vertex point as shown in the image below

One 3D Point Becomes four in 2D

One 3D Point Becomes four in 2D

So, you can see the problem from the figure above. When you unfold a pyramid, uv mapping of 0ne 3D vertex point becomes four 2D points. In this case, the Blender data will give four uv data points for the apex of your pyramid above (point 4: 0,0,0 -> uv:points: 00, 01, 10, 11). But drawTriangles does not know what to do with this. It wants one uv point for each vertex. The way around this problem is to collect all similar uv data points per vertex and assign a new vertex number for non -unique points. So for example,

(point 4: 0,0,0 -> uv:points: 00, 01, 10, 11

becomes,

point 4: 0,0,0 -> 00
point 5: 0,0,0 -> 01
point 6: 0,0,0 -> 10
point 7: 0,0,0 -> 11

Importantly, points 0-3 are the four base pyramid points which are not unwrapped and as a result don’t need to be assigned new vertex numbers. The new vertex numbers have the same vertex coordinates as shown above – only the point assignment for the triangular fan is changed.

Note: The number of extra points you need to add is entirely dependent on how you unfold your object. If you use the hole punch method, you only need four extra vertices for an entire figure. As in anything, there’s no free lunch. You always give up something to gain something.

Code

The code sorts points into unique vertices and uv numbers (creating a 0ne-to-one mapping). If unique data can not be found new vertices are assigned creating a 0ne-to-one mapping as described in the post on the polar cube.

Blender XML Exporter

The whole process starts by creating a Blender XML file and photoshop image. This is done by using the Blender XML Exporter discussed in an earlier post.

The Blender XML file is imported into the program, parsed, and sorted. Then the sorter code below is used to create the one-to-one mapping scheme discussed above. Here are the steps:

1. The code starts by grabbing the index and vertex data created from the Blender XML export.

for (var i:int = 0; i< myFaceNum; i++) {

//Grab Indices from Blender XML
indices.push(int(mySplitFace[12*i]));
indices.push(int(mySplitFace[12*i+1]));
indices.push(int(mySplitFace[12*i+2]));

//Grab UV Data from Blender XML
myUVDatArray.push(Number(mySplitFace[12*i+3]));
myUVDatArray.push(Number(1-mySplitFace[12*i+4]));

myUVDatArray.push(Number(mySplitFace[12*i+5]));
myUVDatArray.push(Number(1-mySplitFace[12*i+6]));

myUVDatArray.push(Number(mySplitFace[12*i+7]));
myUVDatArray.push(Number(1-mySplitFace[12*i+8]));
}

2. The raw data above is sorted and a one-to-one mapping scheme created.

//Ferts Sorting Program
myFertsNum=indices.length;
myVertsNum=verts.length/3-1;//iteration number

for (var j:int = 0; j< myFertsNum; j++) {
for (var k:int = j+1; k<myFertsNum; k++) {
if (indices[j]==indices[k]) {
if ( (myUVDatArray[2*j]==myUVDatArray[2*k]) && (myUVDatArray[2*j+1]==myUVDatArray[2*k+1]) ) {
} else { verts.push(verts[3*indices[k]],verts[3*indices[k]+1],verts[3*indices[k]+2])
myVertsNum++;
indices[k]=myVertsNum; }}}}

3. And the uvtData is extracted.

//Sort uvtData (verts match uvtData-the golden rule for drawTriangles)
for (var m:int = 0; m<verts.length/3; m++) {
for (var n:int = 0; n<indices.length; n++) {
if (indices[n]==m) {
uvtData.push(myUVDatArray[2*n], myUVDatArray[2*n+1], 0);
break; }}}

Important Note!!!

The resulting parser works really well for convex structures, but has difficulty with concave objects. Due to sorting issues.

Both Flash & Math and Dorking Around 3D in Flash (and in one of my previous post) have suggested individual triangle sorting routines, and Dorking Around 3D in Flash has a working textured convex example using triangle sorting. Further testing and development needs to be done in this area: Individual triangle sorting may handle concave figures without a problem, but at present they do not use the drawTriangles method or an XML importer from Blender, as presented in this post.

Encapsulation

The code is fully encapsulated and closely resembles Papervision3D. A primitive is declared and an animation loop created inside a wrapper file (just as in Papervision3D).

blenderHouse = new BlenderPrim(“assets/data/shuttle.xml”, bmp, 300.0, 300.0, 10);

The parameters of the constructor function above are xml, bitmap, width and height. And the Blender Primitive lives in tbe org/lively3d/objects/primitives folder. This is the same as Papervision3D’s primitive path except for the lively3d part which is used to distinguish the different approaches.

Click the more button below to view the wrapper and Blender Primitive classes.

Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.