Category Archives: 3D

Vectorpark Style Hemisphere

Actionscript:
  1. const TWO_PI:Number = Math.PI * 2;
  2. const PI_HALF_PI:Number = Math.PI + Math.PI / 2;
  3. x = stage.stageWidth / 2;
  4. y = stage.stageHeight / 2;
  5.  
  6. var runHemisphere:Function = makeHemisphere(0,0, 100,0xFF0000, 0xFFCC00);
  7. var dx:Number = 0;
  8. var dy:Number = 0;
  9.  
  10. addEventListener(Event.ENTER_FRAME, onLoop);
  11. function onLoop(evt:Event):void {
  12.     dx += (mouseX / 50 - dx) / 4;
  13.     dy += (mouseY - dy) / 4;
  14.     runHemisphere(dx, dy);
  15. }
  16. function makeHemisphere(x:Number, y:Number, size:Number, colA:uint, colB:uint):Function{
  17.     var s:Sprite = Sprite(addChild(new Sprite()));
  18.     s.x = x;
  19.     s.y = y;
  20.     var bg:Sprite = Sprite(s.addChild(new Sprite()));
  21.    
  22.     with (bg.graphics) clear(), beginFill(colA), halfCircle(bg.graphics, 0,0 , size);
  23.     var scol:uint = colB;
  24.     var slice:Sprite = Sprite(s.addChild(new Sprite()));
  25.     return function(theta:Number, rot:Number){
  26.          theta %= TWO_PI;
  27.         if (theta <0){
  28.             theta = TWO_PI - -theta;
  29.         }
  30.         var scale:Number = Math.cos(theta);
  31.         if (theta> 1.57){
  32.             scol = colA;
  33.         } else {
  34.             scol = colB;
  35.         }
  36.         if (theta> Math.PI){
  37.             bg.rotation = 180;
  38.         }else{
  39.             bg.rotation = 0;
  40.         }
  41.         if (theta> PI_HALF_PI){
  42.             scol = colB;
  43.         }
  44.         with(slice.graphics) clear(), beginFill(scol), scaleYcircle(slice.graphics,size, scale);
  45.         s.rotation = rot;
  46.     }
  47. }
  48. // original circle function by senocular (www.senocular.com) from here http://www.actionscript.org/forums/showthread.php3?s=&threadid=30328
  49. function halfCircle(g:Graphics, x:Number,y:Number,r:Number):void {
  50.     var c1:Number = r * (Math.SQRT2 - 1);
  51.     var c2:Number = r * Math.SQRT2 / 2;
  52.     var xr:Number = x + r, yr:Number = y + r;
  53.     var x_r:Number = x - r, yc1:Number = y + c1;
  54.     var yc2:Number = y + c2, xc1:Number = x + c1, xc2:Number = x + c2;
  55.     var x_c1:Number = x - c1;
  56.     g.moveTo(xr, y);
  57.     g.curveTo(xr, yc1, xc2, yc2);
  58.     g.curveTo(xc1, yr, x, yr);
  59.     g.curveTo(x - c1,yr, x - c2, yc2);
  60.     g.curveTo(x_r, yc1, x_r, y);
  61. }
  62. // circle that can be scaled on the y axis
  63. function scaleYcircle(g:Graphics, r:Number, s:Number = 1):void {
  64.     var c1:Number = r * (Math.SQRT2 - 1);
  65.     var c2:Number = r * Math.SQRT2 / 2;
  66.     var rs:Number = r * s, c1s:Number = c1 * s, c2s:Number = c2 * s;
  67.     var x_r:Number =  -r, y_r:Number = -rs, x_c2:Number =  -c2;
  68.     var y_c2:Number =  -c2s, x_c1:Number =  -c1, y_c1:Number =  -c1s
  69.     g.moveTo(r, 0), g.curveTo(r, c1s, c2, c2s);
  70.     g.curveTo(c1, rs, 0, rs), g.curveTo(x_c1,rs, x_c2, c2s);
  71.     g.curveTo(x_r, c1s, x_r, 0), g.curveTo(x_r,y_c1,x_c2,y_c2);
  72.     g.curveTo(x_c1,y_r,0,y_r), g.curveTo(c1,y_r,c2,y_c2);
  73.     g.curveTo(r,y_c1,r,0);
  74. }

The above snippet draws a 3D hemisphere using a technique I first saw at vectorpark.com. Vectorpark.com has been around for years and it's an amazing site... if you've never seen it before I highly recommend spending some time there...

When I decided to post the half-circle snippet yesterday... I knew I would be writing this today. It's one of those things I've always thought about doing, but never gotten around to. I show vectorpark.com to my animation class (almost no coding in that class) and we emulate some of the 3D techniques for simple primitives with pure timeline animation. The above is the first time I've tried to emulate one of these techniques with code.

I was pleasantly surprised when visiting vectorpark.com this morning... Patrick Smith has posted some new work there. Really excellent stuff...

UPDATE:
Katopz converted this to a doc class and put it up on wonderfl...

Also posted in Graphics | Tagged , , | 6 Comments

Polygon Triangulation

Actionscript:
  1. var triangulate:Triangulate = new Triangulate();
  2.  
  3. var poly:Array=[];
  4.  
  5. stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  6. function onDown(evt:MouseEvent):void {
  7.     poly.push(new Pnt(mouseX, mouseY));
  8. }
  9.  
  10. addEventListener(Event.ENTER_FRAME, onLoop);
  11. function onLoop(evt:Event):void {
  12.     var i:int;
  13.     graphics.clear();
  14.     var verts:Array=triangulate.process(poly);
  15.  
  16.     if (verts==null) {
  17.         // draw a red polygon if there is some kind of error,
  18.         // or if there are too few points on the poly
  19.         if (poly.length>1) {
  20.             graphics.lineStyle(0,0xFF0000);
  21.             graphics.moveTo(poly[0].x, poly[0].y);
  22.             for (i = 1; i<poly.length; i++) {
  23.                 graphics.lineTo(poly[i].x, poly[i].y);
  24.             }
  25.         }
  26.     }else{
  27.         // draw the triangulated polygon
  28.         var tcount:int = verts.length / 3;
  29.         graphics.lineStyle(0,0x000000);
  30.         for (i = 0; i<tcount; i++) {
  31.             var index:int = i * 3;
  32.             var p1:Pnt=verts[index];
  33.             var p2:Pnt=verts[index+1];
  34.             var p3:Pnt=verts[index+2];
  35.             graphics.moveTo(p1.x,p1.y);
  36.             graphics.lineTo(p2.x,p2.y);
  37.             graphics.lineTo(p3.x,p3.y);
  38.             graphics.lineTo(p1.x,p1.y);
  39.         }
  40.     }
  41. }

The above demo's a class that triangulates a polygon given a list of points. To test this snippet you'll need the Pnt and Triangulate Classes, which you can download or copy from below.

Polygon triangulation is useful for lots of things... I first found that I needed it back in my Director days. I wanted to be able to draw a polygon and then extrude it into 3D space - in order to do this I needed to triangulate the polygon that was drawn. Luckily there was an undocumented feature in Lingo that did the triangulation. I'll probably do an extrusion demo soon. I've been looking into this to make the QuickBox2D polygon stuff a little easier.


Take a look at the swf here

Download all source and fla here....

Here is the Triangulate class:

Actionscript:
  1. /**
  2. This code is a quick port of code written in C++ which was submitted to
  3. flipcode.com by John W. Ratcliff  // July 22, 2000
  4. See original code and more information here:
  5. http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  6.  
  7. ported to actionscript by Zevan Rosser
  8. www.actionsnippet.com
  9. */
  10.  
  11. package {
  12.    
  13.     public class Triangulate {
  14.        
  15.         private const EPSILON:Number = 0.0000000001;
  16.        
  17.         public function Triangulate(){}
  18.        
  19.         public function process(contour:Array):Array{
  20.             var result:Array = [];
  21.             var n:int = contour.length
  22.             if ( n <3 ) return null
  23.            
  24.             var verts:Array = [];
  25.            
  26.               /* we want a counter-clockwise polygon in verts */
  27.             var v:int
  28.            
  29.               if ( 0.0 <area(contour) ){
  30.                 for (v=0; v<n; v++) verts[v] = v;
  31.               }else{
  32.                 for(v=0; v<n; v++) verts[v] = (n-1)-v;
  33.               }
  34.            
  35.               var nv:int = n;
  36.            
  37.               /*  remove nv-2 vertsertices, creating 1 triangle every time */
  38.               var count:int = 2*nv;   /* error detection */
  39.              var m:int;
  40.               for(m=0, v=nv-1; nv>2; )
  41.               {
  42.                 /* if we loop, it is probably a non-simple polygon */
  43.                 if (0>= (count--)){
  44.                   //** Triangulate: ERROR - probable bad polygon!
  45.                  // trace("bad poly");
  46.                   return null;
  47.                 }
  48.            
  49.                 /* three consecutive vertices in current polygon, <u,v,w> */
  50.                 var u:int = v; if (nv <= u) u = 0;     /* previous */
  51.                 v = u+1; if (nv <= v) v = 0;     /* new v    */
  52.                 var w:int = v+1; if (nv <= w) w = 0;     /* next     */
  53.            
  54.                 if ( snip(contour,u,v,w,nv,verts)){
  55.                   var a:int,b:int,c:int,s:int,t:int;
  56.            
  57.                   /* true names of the vertices */
  58.                   a = verts[u]; b = verts[v]; c = verts[w];
  59.            
  60.                   /* output Triangle */
  61.                   result.push( contour[a] );
  62.                   result.push( contour[b] );
  63.                   result.push( contour[c] );
  64.            
  65.                   m++;
  66.            
  67.                   /* remove v from remaining polygon */
  68.                   for(s=v,t=v+1;t<nv;s++,t++) verts[s] = verts[t]; nv--;
  69.            
  70.                   /* resest error detection counter */
  71.                   count = 2 * nv;
  72.                 }
  73.               }
  74.            
  75.               return result;
  76.         }
  77.        
  78.         // calculate area of the contour polygon
  79.         public function area(contour:Array):Number{
  80.             var n:int = contour.length;
  81.             var a:Number  = 0.0;
  82.            
  83.             for(var p:int=n-1, q:int=0; q<n; p=q++){
  84.                 a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  85.             }
  86.             return a * 0.5;
  87.         }
  88.        
  89.         // see if p is inside triangle abc
  90.         public function insideTriangle(ax:Number, ay:Number, bx:Number, by:Number, cx:Number, cy:Number,px:Number,py:Number):Boolean{
  91.                                                            
  92.               var aX:Number, aY:Number, bX:Number, bY:Number
  93.               var cX:Number, cY:Number, apx:Number, apy:Number;
  94.               var bpx:Number, bpy:Number, cpx:Number, cpy:Number;
  95.               var cCROSSap:Number, bCROSScp:Number, aCROSSbp:Number;
  96.            
  97.               aX = cx - bx;  aY = cy - by;
  98.               bX = ax - cx;  bY = ay - cy;
  99.               cX = bx - ax;  cY = by - ay;
  100.               apx= px  -ax;  apy= py - ay;
  101.               bpx= px - bx;  bpy= py - by;
  102.               cpx= px - cx;  cpy= py - cy;
  103.            
  104.               aCROSSbp = aX*bpy - aY*bpx;
  105.               cCROSSap = cX*apy - cY*apx;
  106.               bCROSScp = bX*cpy - bY*cpx;
  107.            
  108.               return ((aCROSSbp>= 0.0) && (bCROSScp>= 0.0) && (cCROSSap>= 0.0));
  109.         }
  110.        
  111.         private function snip(contour:Array, u:int, v:int, w:int, n:int, verts:Array):Boolean{
  112.               var p:int;
  113.               var ax:Number, ay:Number, bx:Number, by:Number;
  114.               var cx:Number, cy:Number, px:Number, py:Number;
  115.            
  116.                   ax = contour[verts[u]].x;
  117.                   ay = contour[verts[u]].y;
  118.                
  119.                   bx = contour[verts[v]].x;
  120.                   by = contour[verts[v]].y;
  121.                
  122.                   cx = contour[verts[w]].x;
  123.                   cy = contour[verts[w]].y;
  124.            
  125.           if ( EPSILON> (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  126.            
  127.               for (p=0;p<n;p++){
  128.                     if( (p == u) || (p == v) || (p == w) ) continue;
  129.                     px = contour[verts[p]].x
  130.                     py = contour[verts[p]].y
  131.                     if (insideTriangle(ax,ay,bx,by,cx,cy,px,py)) return false;
  132.               }
  133.               return true;
  134.         }
  135.     }
  136. }

... and the Pnt class:

Actionscript:
  1. // Point class, no reason to use AS3's build in Point
  2. package{
  3.     public class Pnt {
  4.         public var x:Number;
  5.         public var y:Number;
  6.         public function Pnt(x:Number, y:Number){
  7.             this.x = x;
  8.             this.y = y;
  9.         }
  10.     }
  11. }

I also found a nice description of the basic technique being employed here.

UPDATE:
This should be obvious, but I was targeting fp9 with this... thus the use of Array instead of Vector.

Also posted in Math, graphics algorithms, misc | Tagged , | 6 Comments

Parametric UV Surface

Actionscript:
  1. var matrix:Matrix3D = new Matrix3D();
  2. var verts:Vector.<Number> = new Vector.<Number>();
  3. var pVerts:Vector.<Number> = new Vector.<Number>();
  4. var uvts:Vector.<Number> = new Vector.<Number>();
  5. var sqrt2:Number = Math.sqrt(2)
  6. var pi:Number = Math.PI;
  7. var pi23:Number= 2 * Math.PI / 3;
  8. var step:Number= pi / 50;
  9. for (var u:Number = -pi; u<pi; u+=step) {
  10.     for (var v:Number = -pi; v<pi; v+=step) {
  11.         // from here http://local.wasp.uwa.edu.au/~pbourke/geometry/hexatorus/
  12.         var px = Math.sin(u) / Math.abs(sqrt2+ Math.cos(v))
  13.         var py = Math.sin(u+pi23) / Math.abs(sqrt2 +Math.cos(v + pi23))
  14.         var pz = Math.cos(u-pi23) / Math.abs(sqrt2 +Math.cos(v - pi23))
  15.         verts.push(px * 50);
  16.         verts.push(py * 50);
  17.         verts.push(pz * 50);
  18.     }
  19. }
  20. var brush:BitmapData=new BitmapData(3,2,true,0x41FFFFFF);
  21. var canvas:BitmapData=new BitmapData(400,400,false,0x000000);
  22. addChild(new Bitmap(canvas));
  23. var dx:Number=0;
  24. var dy:Number=0;
  25. addEventListener(Event.ENTER_FRAME, onLoop);
  26. function onLoop(evt:Event):void {
  27.     dx += (mouseX - dx)/4;
  28.     dy += (mouseY - dy)/4;
  29.     matrix.identity();
  30.     matrix.appendRotation(dy,Vector3D.X_AXIS);
  31.     matrix.appendRotation(dx,Vector3D.Y_AXIS);
  32.     matrix.appendTranslation(200, 200, 0);
  33.     Utils3D.projectVectors(matrix, verts, pVerts, uvts);
  34.     canvas.lock();
  35.     canvas.fillRect(canvas.rect, 0x000000);
  36.     var p = new Point();
  37.     for (var i:int = 0; i<pVerts.length; i+=2) {
  38.         p.x = pVerts[i];
  39.         p.y = pVerts[i+1];
  40.         canvas.copyPixels(brush, brush.rect, p, null, null, true);
  41.     }
  42.     canvas.unlock();
  43. }

More 3D shapes inspired by (taken from) Paul Bourke's website. I figured I should probably add a parametric 3D surface to this set of posts - so I chose to plot the Triaxial Hexatorus. It's important to note that U and V go from -PI to PI.

I googled Triaxial Hexatorus and stumbled upon a great papervision demo that creates meshes using parametric equations - it also morphs between shapes.

I also noticed that I don't need to populate the uvts or pVerts Vectors with zeros - seems to work fine without doing that.

Also posted in BitmapData, Math, Vector, graphics algorithms, pixel manipulation | Tagged , | Leave a comment

Wormhole

Actionscript:
  1. var matrix:Matrix3D = new Matrix3D();
  2. var verts:Vector.<Number> = new Vector.<Number>();
  3. var pVerts:Vector.<Number> = new Vector.<Number>();
  4. var uvts:Vector.<Number> = new Vector.<Number>();
  5. for (var i:Number = -10; i<10; i+=.04) {
  6.     for (var j:Number = -5; j<8; j+=.04) {
  7.         for (var k:Number = -10; k<10; k+=.04) {
  8.             var s:Number =  i * i * j + j * k * k;
  9.             if (s <10 && s> 9.95) {
  10.                 verts.push(i * 20);
  11.                 verts.push(j * 20);
  12.                 verts.push(k * 20);
  13.                 pVerts.push(0),pVerts.push(0);
  14.                 uvts.push(0),uvts.push(0),uvts.push(0);
  15.             }
  16.         }
  17.     }
  18. }
  19. var brush:BitmapData=new BitmapData(3,2,true,0x41FFFFFF);
  20. var canvas:BitmapData=new BitmapData(400,400,false,0x000000);
  21. addChild(new Bitmap(canvas));
  22. var dx:Number=0;
  23. var dy:Number=0;
  24. addEventListener(Event.ENTER_FRAME, onLoop);
  25. function onLoop(evt:Event):void {
  26.     dx += (mouseX - dx)/4;
  27.     dy += (mouseY - dy)/4;
  28.     matrix.identity();
  29.     matrix.appendRotation(dy,Vector3D.X_AXIS);
  30.     matrix.appendRotation(dx,Vector3D.Y_AXIS);
  31.     matrix.appendTranslation(200, 200, 0);
  32.     Utils3D.projectVectors(matrix, verts, pVerts, uvts);
  33.     canvas.lock();
  34.     canvas.fillRect(canvas.rect, 0x000000);
  35.     var p = new Point();
  36.     for (var i:int = 0; i<pVerts.length; i+=2) {
  37.         p.x = pVerts[i];
  38.         p.y = pVerts[i+1];
  39.         canvas.copyPixels(brush, brush.rect, p, null, null, true);
  40.     }
  41.     canvas.unlock();
  42. }

Yet another variation on the post from the last two days. This one plots something resembling a wormhole - I was randomly tweaking the equation for a sphere and stumbled upon this...

Also posted in BitmapData, Math, Vector, graphics algorithms, pixel manipulation | Tagged , | Leave a comment