Category Archives: Vector

Sphere of Squares

Actionscript:
  1. [SWF(width = 600, height = 600, backgroundColor=0x000000)]
  2. var squareNum:int  = 1000;
  3. var hw:Number = stage.stageWidth / 2;
  4. var hh:Number = stage.stageHeight / 2;
  5. // verts defines a single square
  6. var verts:Vector.<Number> = Vector.<Number>([-20, 0, 0, 20, 0, 0, 20, 0, 40, -20, 0, 40, -20, 0, 0]);
  7. var cmds:Vector.<int> = Vector.<int>([1,2,2,2,2]);
  8. var tempVerts:Vector.<Number> = new Vector.<Number>();
  9. var newVerts:Vector.<Number> = new Vector.<Number>();
  10. var pVerts:Vector.<Number> = new Vector.<Number>(10 * squareNum);
  11. var uv:Vector.<Number> = new Vector.<Number>(15 * squareNum);
  12. var vectors:Shape = new Shape();
  13. var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
  14. addChild(new Bitmap(canvas));
  15. var blurred:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
  16. var blur:BlurFilter = new BlurFilter(20,20,1);
  17.  
  18. var m:Matrix3D = new Matrix3D();
  19.  
  20. var radius:Number = 200;
  21. // duplicate the verts array a bunch of times
  22. // each time moving the square to a random place on the
  23. // circumference of a sphere
  24. for (var i:int = 0; i<squareNum; i++){
  25.     m.identity();
  26.     var s:Number = Math.random()*.5 + .5;
  27.     m.appendScale(s, s, s);
  28.     m.appendRotation(90,Vector3D.X_AXIS);
  29.     m.appendTranslation(0, 0, radius);
  30.     m.appendRotation(Math.random()*360,Vector3D.X_AXIS);
  31.     m.appendRotation(Math.random()*360,Vector3D.Y_AXIS);
  32.     m.appendRotation(Math.random()*360,Vector3D.Z_AXIS);
  33.     m.transformVectors(verts,tempVerts);
  34.     newVerts = newVerts.concat(tempVerts);
  35.     cmds = cmds.concat(Vector.<int>([1,2,2,2,2]));
  36. }
  37. newVerts.fixed = pVerts.fixed = uv.fixed = true;
  38. var dx:Number = 0, dy:Number = 0;
  39. var pnt:Point = new Point();
  40. addEventListener(Event.ENTER_FRAME, onLoop);
  41. function onLoop(evt:Event):void {
  42.        dx += (mouseX - dx) / 4;
  43.        dy += (mouseY - dy) / 4;
  44.        m.identity();
  45.        m.appendRotation(dx,Vector3D.Z_AXIS);
  46.        m.appendRotation(dy,Vector3D.X_AXIS);
  47.        m.appendTranslation(hw,hh, 0);
  48.        Utils3D.projectVectors(m, newVerts, pVerts, uv);
  49.        with(vectors.graphics){
  50.            clear();
  51.            beginFill(0xFFFFFF);
  52.            drawCircle(hw, hh, radius+10);
  53.            beginFill(0x000000);
  54.            drawPath(cmds, pVerts, GraphicsPathWinding.NON_ZERO);
  55.        }
  56.        canvas.fillRect(canvas.rect, 0x000000);
  57.        canvas.draw(vectors);
  58.        blurred.copyPixels(canvas, canvas.rect, pnt);
  59.        blurred.applyFilter(blurred,blurred.rect, pnt, blur);
  60.        canvas.draw(blurred, null, null, BlendMode.SCREEN);
  61. }

This snippet is similar to yesterdays post but the visual result is rather different. This one does a little more Matrix3D stuff resulting in a sphere made up entirely of squares. This is obscured by the size of the squares and the fact that they overlap and cut each other up. BitmapData a BlurFilter and a BlendMode give the entire thing a slight glow...


Have a look at the swf here...

Also posted in 3D, BitmapData | Tagged , , , | 12 Comments

transformVectors() and drawPath()

Actionscript:
  1. var squareNum:int  = 100;
  2. // verts defines a single square
  3. var verts:Vector.<Number> = Vector.<Number>([-20, 0, 0, 20, 0, 0, 20, 0, 40, -20, 0, 40, -20, 0, 0]);
  4. var cmds:Vector.<int> = Vector.<int>([1,2,2,2,2]);
  5. var tempVerts:Vector.<Number> = new Vector.<Number>();
  6. var newVerts:Vector.<Number> = new Vector.<Number>();
  7. var pVerts:Vector.<Number> = new Vector.<Number>(10 * squareNum);
  8. var uv:Vector.<Number> = new Vector.<Number>(15 * squareNum);
  9.  
  10. var m:Matrix3D = new Matrix3D();
  11.  
  12. // duplicate the verts array a bunch of times
  13. // each time randomly rotating, scaling and translating it
  14. for (var i:int = 0; i<squareNum; i++){
  15.     m.identity();
  16.     m.appendRotation(Math.random()*360,Vector3D.X_AXIS);
  17.     m.appendRotation(Math.random()*360,Vector3D.Y_AXIS);
  18.     m.appendRotation(Math.random()*360,Vector3D.Z_AXIS);
  19.     var s:Number = Math.random()*2 + .1;
  20.     m.appendScale(s, s, s);
  21.     m.appendTranslation(Math.random()*400 - 200, Math.random()*400 - 200, Math.random()*400 - 200);
  22.     m.transformVectors(verts,tempVerts);
  23.     newVerts = newVerts.concat(tempVerts);
  24.     cmds = cmds.concat(Vector.<int>([1,2,2,2,2]));
  25. }
  26. newVerts.fixed = pVerts.fixed = uv.fixed = true;
  27.  
  28. var dx:Number = 0, dy:Number = 0;
  29. addEventListener(Event.ENTER_FRAME, onLoop);
  30. function onLoop(evt:Event):void {
  31.        dx += (mouseX - dx) / 4;
  32.        dy += (mouseY - dy) / 4;
  33.        
  34.        m.identity();
  35.        m.appendRotation(dx,Vector3D.Z_AXIS);
  36.        m.appendRotation(dy,Vector3D.X_AXIS);
  37.        m.appendTranslation(stage.stageWidth / 2,stage.stageHeight / 2, 0);
  38.  
  39.        Utils3D.projectVectors(m, newVerts, pVerts, uv);
  40.        
  41.        graphics.clear();
  42.        graphics.lineStyle(0,0x000000);
  43.        graphics.drawPath(cmds, pVerts);
  44. }

This is a demo showing how to use transformVectors() and drawPath() together. It creates 100 wireframe squares in 3D:


Have a look at the swf...

Also posted in 3D, Graphics | 2 Comments

setVector vs copyPixels

Actionscript:
  1. var brushNum:int = 10000;
  2. var canvas:BitmapData = new BitmapData(800,600,false, 0x000000);
  3. addChild(new Bitmap(canvas));
  4.  
  5. var shape:Shape = new Shape();
  6. with(shape.graphics) beginFill(0xFF0000), drawCircle(10,10,5);
  7. shape.filters = [new BlurFilter(6, 6, 4)];
  8.  
  9. var brush:BitmapData = new BitmapData(20, 20, false, 0x000000);
  10. brush.draw(shape, shape.transform.matrix);
  11.  
  12.  
  13.  
  14. // make sure brushVect is fixed length
  15. var brushVect:Vector.<uint> = new Vector.<uint>(brush.width * brush.height, true);
  16. var tempVect:Vector.<uint> =  brush.getVector(brush.rect);
  17. var i:int = 0;
  18. // quick hack to retain fixed length
  19. for (i = 0; i<brushVect.length; i++){
  20.     brushVect[i] = tempVect[i];
  21. }
  22.  
  23. canvas.setVector(brush.rect, brushVect);
  24.  
  25. var pnt:Point = new Point();
  26. var brushRect:Rectangle = brush.rect;
  27. var destRect:Rectangle = brushRect.clone();
  28. var locX:Vector.<Number> = new Vector.<Number>(brushNum, true);
  29. var locY:Vector.<Number> = new Vector.<Number>(brushNum, true);
  30. for (i= 0; i<brushNum; i++){
  31.     locX[i] = Math.random() * stage.stageWidth - 10;
  32.     locY[i] = Math.random() * stage.stageHeight - 10;
  33. }
  34.  
  35. var iterations:int = 50;
  36. var timer:Number;
  37. var avg:Vector.<Number> = new Vector.<Number>();
  38. trace("copyPixels");
  39. addEventListener(Event.ENTER_FRAME, onLoop);
  40. function onLoop(evt:Event):void {
  41.        canvas.fillRect(canvas.rect, 0x000000);
  42.        var i:int = brushNum;
  43.        if (drawMode == "copyPixels"){
  44.            timer = getTimer();
  45.            canvas.lock();
  46.            while(--i> -1){
  47.                 pnt.x = locX[i];
  48.                 pnt.y = locY[i];
  49.                 // copyPixels can easily do alpha manipulation, setVector cannot (see comment below);
  50.                 canvas.copyPixels(brush, brushRect, pnt);//, null, null, true);
  51.            }
  52.            canvas.unlock();
  53.            avg.push(getTimer() - timer);
  54.        }else{
  55.            timer = getTimer();
  56.            canvas.lock();
  57.            while(--i> -1){
  58.                destRect.x = locX[i];
  59.                destRect.y = locY[i];
  60.                canvas.setVector(destRect, brushVect);
  61.            }
  62.            canvas.unlock();
  63.            avg.push(getTimer() - timer);
  64.        }
  65.        // take an average of iterations iterations
  66.        if (avg.length == iterations){
  67.            var average:Number = 0;
  68.            for (i = 0; i<iterations; i++){
  69.                  average += avg[i];
  70.            }
  71.            trace(average / iterations);
  72.            avg = new Vector.<Number>();
  73.        }
  74. }
  75.  
  76. var drawMode:String = "copyPixels";
  77. stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
  78. function onKeyReleased(evt:Event):void{
  79.     avg = new Vector.<Number>();
  80.     drawMode = (drawMode == "copyPixels") ? "setVector" : "copyPixels"
  81.     trace(drawMode);
  82. }

In the comments of a post from a few days back, Piergiorgio Niero mentioned that setVector may be faster than copyPixels. To see if this was true, Piergiorgio and I each tried a few things and while Piergiorgio seemed to reach some conclusions... I wasn't sure we had properly tested to see which one was actually faster.

I created the above snippet to help test to see which is indeed faster. This snippet draws 10,000 small 20x20 pixel graphics to the stage. There is no animation because I wanted to try and isolate the speed of the setVector and copyPixels calls. These are the results on my macbook pro 2.4 ghz duo:

// average speed of 50 iterations of drawing
copyPixels
15.1
15.68
15.44
15.46
15.62
15.74
15.68
setVector
32.6
32.6
31.1
32.1
32.82
32.54
copyPixels
15.48
15.62
15.74
15.46
15.42
15.44
15.64
setVector
32.62
32.8
33.08
32.48
32.74
32.32

If you interested in this, post your results in the comments along with the type of computer you're using. I have a feeling there will be a wide variety of results... just make sure you're not using the flash debug player, as that can act significantly different than the release version of the player.

setVector() and copyPixels() Usage

Something to note here is that setVector and copyPixels aren't normally suitable for the same thing. copyPixels is used to move a rectangle of pixels from one BitmapData to another - you can easily do advanced alpha channel manipulation and scaling with it and you don't have to do pixel by pixel logic. setVector is used to do pixel by pixel manipulation - it is a sort of mature/advanced setPixel function that allows you to do logic on a Vector of uints and then set the pixels of a rectangular region of a BitmapData object equal to the data within that Vector. So if you need to do alpha manipulation or image scaling with setVector you'll find yourself running into some more advanced programming than copyPixels requires... and if you tried to do pixel by pixel manipulation with copyPixels... well, that just isn't what it was meant to be used for...

I'm always wary of these kind of speed tests... if anyone has suggestions about how to improve this test, please feel free to comment.

UPDATE katopz pointed out I should use fixed length Vectors... so I changed the brushVect instantiation code slightly. I didn't do it for the avg vector because it only has 50 values and it doesn't help improve the speed of setVector and copyPixels in any way and complicates the code slightly... it's hard to decide which optimization techniques you should choose to make habbit and which ones you should only whip out when you need speed...

Also posted in BitmapData | 7 Comments

Cut Image into Squares (copyPixels)

Actionscript:
  1. [SWF(width=650, height=650)]
  2. var loader:Loader = new Loader();
  3. loader.load(new URLRequest("http://actionsnippet.com/wp-content/chair.jpg"));
  4. loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
  5.  
  6. var w:Number;
  7. var h:Number;
  8. var rows:Number = 20;
  9. var cols:Number = 20;
  10. var tiles:Vector.<BitmapData> = new Vector.<BitmapData>();
  11. var locX:Vector.<Number> = new Vector.<Number>();
  12. var locY:Vector.<Number> = new Vector.<Number>();
  13. var rX:Vector.<Number> = new Vector.<Number>();
  14. var rY:Vector.<Number> = new Vector.<Number>();
  15. var sX:Vector.<Number> = new Vector.<Number>();
  16. var sY:Vector.<Number> = new Vector.<Number>();
  17. function onLoaded(evt:Event):void{
  18.     w = evt.target.width;
  19.     h = evt.target.height;
  20.     var image:BitmapData = Bitmap(evt.target.content).bitmapData;
  21.     var tileWidth:Number = w / cols;
  22.     var tileHeight:Number = h / rows;
  23.     var inc:int = 0;
  24.     var pnt:Point = new Point();
  25.     var rect:Rectangle = new Rectangle(0,0,tileWidth,tileHeight);
  26.     for (var i:int = 0; i<rows; i++){
  27.         for (var j:int = 0; j<cols; j ++){
  28.              var currTile:BitmapData= new BitmapData(tileWidth, tileHeight, true, 0x00000000);
  29.              rect.x = j * tileWidth;
  30.              rect.y = i * tileHeight;
  31.              currTile.copyPixels(image, rect, pnt, null, null, true);
  32.              tiles[inc] = currTile;
  33.              rect.x += 25;
  34.              rect.y += 25;
  35.              sX[inc] = rect.x;
  36.              sY[inc] = rect.y;
  37.              locX[inc] = rX[inc] = -rect.width * 2
  38.              locY[inc] = rY[inc] =  Math.random() * stage.stageHeight;
  39.              setTimeout(startAnimation, inc *4 + 100, inc, rect.x, rect.y);
  40.              inc++;
  41.         }
  42.     }
  43. }
  44.  
  45. function startAnimation(index:int, dx:Number, dy:Number):void{
  46.     var interval:Number;
  47.     var animate:Function = function(index:int):void{
  48.         locX[index] += (dx - locX[index]) / 4;
  49.         locY[index] += (dy - locY[index]) / 4;
  50.         if (Math.abs(locX[index] - dx) <1 && Math.abs(locY[index] - dy)<1){
  51.             locX[index] = dx;
  52.             locY[index] = dy;
  53.             clearInterval(interval);
  54.         }
  55.     }
  56.    interval = setInterval(animate, 32, index);
  57. }
  58.  
  59. var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xFFFFFF);
  60. addChild(new Bitmap(canvas));
  61.  
  62. var loc:Point = new Point();
  63. addEventListener(Event.ENTER_FRAME, onLoop);
  64. function onLoop(evt:Event):void {
  65.       canvas.fillRect(canvas.rect, 0xFFFFFF);
  66.       for (var i:int = 0; i<tiles.length; i++){
  67.             var tile:BitmapData= tiles[i];
  68.             loc.x = locX[i];
  69.             loc.y = locY[i];
  70.             canvas.copyPixels(tile, tile.rect, loc, null, null, true);
  71.       }
  72. }

This snippet cuts a dynamically loaded image into a series of smaller BitmapData instances. These BitmapData instances are then drawn to a canvas BitmapData using copyPixels. The BitmapData.copyPixels() method is extremely fast - so this has some advantages over yesterdays post (which did basically the same thing with Sprites). I used setInterval and setTimeout to do a simple demo animation, but I recommend using TweenLite on a real project.

Also posted in BitmapData | Tagged , , | 10 Comments