Latest snippets

drawPath() Boxes

const TWO_PI:Number = Math.PI * 2;
var boxNum:int = 3000;
var pointNum:int = boxNum * 10;
var rot:Vector.<Number> = new Vector.<Number>();
var posX:Vector.<Number> = new Vector.<Number>();
var posY:Vector.<Number> = new Vector.<Number>();
var velX:Vector.<Number> = new Vector.<Number>();
var velY:Vector.<Number> = new Vector.<Number>();
var scale:Vector.<Number> = new Vector.<Number>();
var rotSpeed:Vector.<Number> = new Vector.<Number>();
var geometry:Vector.<Number> = new Vector.<Number>();
var cmds:Vector.<int> = new Vector.<int>();

var stageWidth:Number = stage.stageWidth;
var stageHeight:Number = stage.stageHeight;

populateGeom();
function populateGeom():void{
	for (var i:int = 0; i<pointNum; i+=10){
		posX.push(Math.random() * stageWidth);
		posY.push(Math.random() * stageHeight);
		velX.push(Math.random()*4 - 2);
		velY.push(Math.random()*4 - 2);
		scale.push(Math.random() * 1 + .2);
		rot.push(Math.random() * TWO_PI);
		rotSpeed.push(Math.random() * 0.2 - 0.1);
		geometry[i] = 0;
		geometry[i + 1] = 0;
		cmds.push(1);
		geometry[i + 2] =  0;
		geometry[i + 3] =  0;
		cmds.push(2);
		geometry[i + 4] =  0;
		geometry[i + 5] =  0;
		cmds.push(2);
		geometry[i + 6] = 0;
		geometry[i + 7] =  0;
		cmds.push(2);
		geometry[i + 8] =  0;
		geometry[i + 9] =  0;
		cmds.push(2);
	}
}

function run():void{
	var inc:int = 0;
	var xt:Number, yt:Number, s:Number, r:Number, rs:Number;
	var cos:Number, sin:Number;
	var cosN:Number, cosP:Number, sinN:Number, sinP:Number;
	for (var i:int = 0; i<pointNum; i+=10){
		xt = posX[inc] += velX[inc];
		yt = posY[inc] += velY[inc];
		
		if (xt < 0 || xt > stageWidth){
			velX[inc] *= -1;
		}
		if (yt < 0 || yt > stageHeight){
			velY[inc] *= -1;
		}
		 
		s = scale[inc];
		r = rot[inc] += rotSpeed[inc];
		inc++;
		 
		cos = Math.cos(r);
		sin = Math.sin(r);
		
        cosN = -10  * cos;
		cosP = 10  * cos
		sinN = -10 * sin;
		sinP = 10 * sin;
		geometry[i] = xt + (cosN - sinN) * s;
		geometry[i + 1] = yt + (cosN + sinN) * s;
		geometry[i + 2] = xt + (cosP - sinN) * s;
		geometry[i + 3] = yt + (cosN + sinP) * s;
		geometry[i + 4] = xt + (cosP - sinP) * s;
		geometry[i + 5] = yt + (cosP + sinP) * s;
		geometry[i + 6] = xt + (cosN - sinP) * s;
		geometry[i + 7] = yt + (cosP + sinN) * s;
		geometry[i + 8]  = geometry[i];
		geometry[i + 9]  = geometry[i + 1];
	}
}

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
     run();
	 graphics.clear();
	 graphics.beginFill(0x000000);
	 graphics.drawPath(cmds, geometry,GraphicsPathWinding.NON_ZERO);
	 graphics.endFill();
}

I was messing with drawPath() today and did this snippet as a sort of performance test… the code isn’t fully optimized but it’s clear that drawPath() is rather fast. I wish that there were beginFill() and lineStyle() drawing commands that worked with it though… oh yeah, that’s what IGraphicsData is for…

Bounds 3 Ways

// make a complex poly and position it randomly
var poly:Sprite = Sprite(addChild(new Sprite()));
poly.graphics.lineStyle(3, 0xFF0000);
poly.graphics.beginFill(0x00FF00);
for (var i:int = 0; i<10; i++) {
	poly.graphics.lineTo(Math.random()*100 - 50, Math.random()*100 - 50);
}
poly.x=Math.random()*stage.stageWidth;
poly.y=Math.random()*stage.stageHeight;

// get bound information:

// is in pixels (whole numbers)
trace("pixelBounds: ", poly.transform.pixelBounds);
// doesn't include stroke width
trace("getBounds: ", poly.getBounds(this));
// includes stroke width
trace("getRect: ", poly.getRect(this));

Three different ways to get the boundaries of a DisplayObject.

More Messy Code

var size:Number = 800;
var canvas:BitmapData = new BitmapData(size,size,false, 0x000000);
addChild(new Bitmap(canvas, "auto", true));

scaleX = scaleY = .5;
var pix:Number = size * size;
var scale:Number = 1/(size/3);

for (var i:Number = 0; i<pix; i++){
       var xp:Number = (i % size);
       var yp:Number = int(i / size);
	   var xt:Number = xp * scale;
	   var yt:Number = yp * scale;
       var ca:Number =  (Math.abs(Math.tan(yt) * Math.pow(Math.sin(xt),3)) * 100 ) % 155;
       var cb:Number =  (Math.abs(Math.tan(xt) * Math.pow(Math.sin(yt),3)) * 100)  % 155;
       ca|= cb;
       canvas.setPixel(xp, yp,  ca << 16 | ca << 8 | ca);
}

Another messy code snippet that I e-mailed to myself at some point…

Try replacing line 16 with some of these variations:

ca &= cb;
ca += cb;
ca -= cb;
ca ^= cb;
ca %= cb

Instantiate and Set Properties

function create(obj:Class, props:Object):*{
	var o:* = new obj();
	for (var p:String in props){
		o[p] = props[p];
	}
	return o;
}

// test out the function

var txt:TextField = create(TextField, {x:200, y:100, selectable:false, text:"hello there", textColor:0xFF0000, defaultTextFormat:new TextFormat("_sans", 20)});
addChild(txt);

var s:Sprite = Sprite(addChild(create(Sprite, {x:100, y:100, rotation:45, alpha:.5})));

with (s.graphics) beginFill(0xFF0000), drawRect(-20,-20,40,40);

var blur:BlurFilter = create(BlurFilter, {blurX:2, blurY:8, quality:1});

s.filters = [blur];

This snippet shows a function called create() that takes two arguments. The first argument is the name of a class to instantiate. The second is an Object with a list of properties to set on a newly created instance of the class (referenced in the first argument).

This could be particularly useful for TextFields which for some reason have no arguments in their constructor.

This will currently only work for classes that have either all optional constructor arguments or no constructor arguments.

Messy Code

var xp:Number=0,yp:Number=0;
var r:Number=0,t:Number=0;
var speed:Number=.01;
var scale:Number=10;
var shape:Shape = Shape(addChild(new Shape()));
shape.x=stage.stageWidth/2;
shape.y=stage.stageHeight/2;
shape.graphics.lineStyle(0,0x000000);

var s:Number=100;
var range:Number=.2;
var b:Number=20;
var a:Number =b*range;

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	range=.2;
	b=20;
	a=b*range;
	t=0;
	shape.graphics.clear();
	shape.graphics.lineStyle(0,0);
	for (var i:int = 0; i<6000; i++) {
		var sin:Number=Math.cos(t*int(mouseY/20));
		r =  Math.sqrt(40 * b * (b - a * (Math.pow(sin, int(mouseX/20)))));
		xp=r*Math.cos(t);
		yp=r*Math.sin(t);

		if (t==0) {
			shape.graphics.lineStyle(0, 0);
			shape.graphics.moveTo(xp, yp);
		} else {
			shape.graphics.lineTo(xp, yp);
		}
		t+=speed;
		if (t > (2 * Math.PI + speed)) {
			range+=.3;
			a=b*range;
			t=0;
		}
	}
}

This is an example of raw messy code that draws some interesting shapes. I was waiting somewhere with my laptop a few weeks back and I wrote this and e-mailed this to myself – it’s completely unoptimized and unedited.

I was working on documentation for QuickBox2D today but didn’t finish it – so I posted this instead. I hope to finish the docs for tomorrow…

Distance Render

var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uvts:Vector.<Number> = new Vector.<Number>();

var hs:Number = 2.3;
var step:Number = 0.04;

var tVerts:Vector.<Number> = new Vector.<Number>();
var rVerts:Vector.<Number> = new Vector.<Number>();
var matrix:Matrix3D = new Matrix3D();
matrix.identity();
matrix.appendRotation(45,Vector3D.Y_AXIS);
matrix.appendRotation(45,Vector3D.X_AXIS);
var inc:int = 0;
var i:Number, j:Number, k:Number;
i = hs;
while( i > -hs){
	j = hs;
	while(j > -hs){
		k = hs;
		while(k > -hs){
			tVerts[inc] = -i;
			inc++
			tVerts[inc] = -j;
			inc++
			tVerts[inc] = -k;
			inc++
			k -= step;
		}
		j -= step;
	}
	i -= step;
}

matrix.transformVectors(tVerts, rVerts);
 
var vinc:int = 0;
inc = 0
var R:Number = 1.5;
var r:Number = .5;
for (i= -hs; i<hs; i+=step){
	for (j = -hs; j<hs; j+=step){
		for (k = -hs; k<hs; k+=step){
			var vx:Number = rVerts[inc] ;
			inc++
			var vy:Number = rVerts[inc]  ;
			inc++
			var vz:Number=  rVerts[inc] ;
			inc++
			var s:Number = Math.pow(vx  * vx  + vy * vy + vz * vz + R*R - r * r, 2) - 4 * (R * R)*(vx * vx + vy * vy); 
			if (s <0 && s > -.5){ 
				verts[vinc] = (i * 50);
				vinc++
				verts[vinc] = (j * 50);
				vinc++
				verts[vinc] = (k * 50);
				vinc++
				  inc += int((hs - k) / step) * 3;
				  k = hs;
			 }
		}
	}
}

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));
render();
function render():void{
	matrix.identity();
    matrix.appendTranslation(200, 200, 0);
	Utils3D.projectVectors(matrix, verts, pVerts, uvts);
	canvas.lock();
	canvas.fillRect(canvas.rect, 0x000000);
	var inc:int = 2;
	var c:int = 0;
	var r:Rectangle = new Rectangle();
	r.width = r.height = 2;
	for (var i:int = 0; i<pVerts.length; i+=2){
		  r.x = pVerts[i];
		  r.y = pVerts[i + 1];
		  c = Math.max(0,100 - verts[inc]);
		  canvas.fillRect(r, c << 16 | c << 8 | c);
		  inc += 3; 
	}
	canvas.unlock();
}

This snippet uses some of the techniques from the last few posts to create a distance render – this renders the implicit equation for a torus.

Array.push() Vector.push() Optimization

var tVerts:Vector.<Number> = new Vector.<Number>();
var inc:int = 0;
var t:Number, i:Number, j:Number, k:Number;
 
 // fast way
t = getTimer();
for (i= -2; i<2; i+=.03){
	for (j = -2; j<2; j+=.03){
		for (k = -2; k<2; k+=.03){
			tVerts[inc] = i;
			inc++;
			tVerts[inc] = j;
			inc++;
			tVerts[inc]= k;
			inc++;
		}
	}
}
trace(getTimer() - t);

tVerts  = new Vector.<Number>();

// slow way
t = getTimer();
for (i= -2; i<2; i+=.03){
	for (j = -2; j<2; j+=.03){
		for (k = -2; k<2; k+=.03){

			tVerts.push(i, j, k);
		//	tVerts.push(j);
		//	tVerts.push(k);
		}
	}
}
trace(getTimer() - t);

Today I needed to populate a Vector in the above manner… populating the vector using push() was quite slow in this case because (among other reasons) push() is a method call. I was curious how much faster populating the Vector without push would be… so I wrote this snippet – in this case it was significantly faster – took less than a third of the time. You can run this snippet to see what kind of results you get.

It’s important to note that this nested for loop could be optimized further but I wanted to focus on the push() optimization alone.

Warning

The most HORRIBLE thing about testing the speed of ActionScript code is that you CANNOT rely on the debug player to test optimizations. Always use the release version of the flash player. The debug player will give unusual (usually slower) results…

Parametric UV Surface

var matrix:Matrix3D = new Matrix3D();
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uvts:Vector.<Number> = new Vector.<Number>();
var sqrt2:Number = Math.sqrt(2)
var pi:Number = Math.PI;
var pi23:Number= 2 * Math.PI / 3;
var step:Number= pi / 50;
for (var u:Number = -pi; u<pi; u+=step) {
	for (var v:Number = -pi; v<pi; v+=step) {
		// from here http://local.wasp.uwa.edu.au/~pbourke/geometry/hexatorus/
		var px = Math.sin(u) / Math.abs(sqrt2+ Math.cos(v))
        var py = Math.sin(u+pi23) / Math.abs(sqrt2 +Math.cos(v + pi23))
        var pz = Math.cos(u-pi23) / Math.abs(sqrt2 +Math.cos(v - pi23))
		verts.push(px * 50);
		verts.push(py * 50);
		verts.push(pz * 50);
	}
}
var brush:BitmapData=new BitmapData(3,2,true,0x41FFFFFF);
var canvas:BitmapData=new BitmapData(400,400,false,0x000000);
addChild(new Bitmap(canvas));
var dx:Number=0;
var dy:Number=0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	dx += (mouseX - dx)/4;
	dy += (mouseY - dy)/4;
	matrix.identity();
	matrix.appendRotation(dy,Vector3D.X_AXIS);
	matrix.appendRotation(dx,Vector3D.Y_AXIS);
	matrix.appendTranslation(200, 200, 0);
	Utils3D.projectVectors(matrix, verts, pVerts, uvts);
	canvas.lock();
	canvas.fillRect(canvas.rect, 0x000000);
	var p = new Point();
	for (var i:int = 0; i<pVerts.length; i+=2) {
		p.x = pVerts[i];
		p.y = pVerts[i+1];
		canvas.copyPixels(brush, brush.rect, p, null, null, true);
	}
	canvas.unlock();
}

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.

Wormhole

var matrix:Matrix3D = new Matrix3D();
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uvts:Vector.<Number> = new Vector.<Number>();
for (var i:Number = -10; i<10; i+=.04) {
	for (var j:Number = -5; j<8; j+=.04) {
		for (var k:Number = -10; k<10; k+=.04) {
			var s:Number =  i * i * j + j * k * k;
			if (s <10 && s > 9.95) {
				verts.push(i * 20);
				verts.push(j * 20);
				verts.push(k * 20);
				pVerts.push(0),pVerts.push(0);
				uvts.push(0),uvts.push(0),uvts.push(0);
			}
		}
	}
}
var brush:BitmapData=new BitmapData(3,2,true,0x41FFFFFF);
var canvas:BitmapData=new BitmapData(400,400,false,0x000000);
addChild(new Bitmap(canvas));
var dx:Number=0;
var dy:Number=0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	dx += (mouseX - dx)/4;
	dy += (mouseY - dy)/4;
	matrix.identity();
	matrix.appendRotation(dy,Vector3D.X_AXIS);
	matrix.appendRotation(dx,Vector3D.Y_AXIS);
	matrix.appendTranslation(200, 200, 0);
	Utils3D.projectVectors(matrix, verts, pVerts, uvts);
	canvas.lock();
	canvas.fillRect(canvas.rect, 0x000000);
	var p = new Point();
	for (var i:int = 0; i<pVerts.length; i+=2) {
		p.x = pVerts[i];
		p.y = pVerts[i+1];
		canvas.copyPixels(brush, brush.rect, p, null, null, true);
	}
	canvas.unlock();
}

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…