Browse the notebook

Category: matrix

Blobby WebGL

Still speed-coding shorts for youtube these last few months… – move your mouse over the codepen below – click and hold to zoom out 😀

https://www.youtube.com/@zevanrosser/shorts

Read snippet: Blobby WebGL

~20,000 Rollovers

[SWF(width = 500, height = 500, frameRate = 30)]

var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xFFFFFF);

var indexCanvas:BitmapData = new BitmapData(stage.stage.stageWidth, stage.stageHeight, false,
										    0xFFFFFF);
addChild(new Bitmap(canvas));

var s:Shape = new Shape();

var lineData:Array = [];
var dataIndex:int = 0;

trace(0xFFFFFF - 1)
var totalLines:int = 20000;
var iterations:int = 9;
var linesPerIter:int = totalLines / iterations;

var xp:int = stage.stageWidth / 2;
var yp:int = stage.stageHeight / 2;

var stepAmt:Number = 60;
var halfStepAmt:Number = stepAmt / 2;

addEventListener(Event.ENTER_FRAME, onDraw);
function onDraw(evt:Event):void {
     if (lineData.length < totalLines){
		generateData(linesPerIter); 
	 }else{
		stage.quality = "high";
		addChild(s);
		s.x = 0;
		s.y = 0;
		 
		removeEventListener(Event.ENTER_FRAME, onDraw);
		addEventListener(Event.ENTER_FRAME, onRun);
	 }
}

function onRun(evt:Event):void {
   var currentIndex:int = indexCanvas.getPixel(mouseX, mouseY);	
   var currentLine:Array = lineData[currentIndex];
   
   s.graphics.clear();
   if (currentIndex != 0xFFFFFF){
		  s.graphics.lineStyle(3, 0xFF0000);
		  s.graphics.moveTo(currentLine[0], currentLine[1]);
		  s.graphics.lineTo(currentLine[2], currentLine[3]);  
   }
}

function generateData(num:int):void{
	var rxA:int, rxB:int, ryA:int, ryB:int;	
	var g:Graphics = s.graphics;
	for (var i:int = 0; i<num; i++){
		rxA = xp;
		ryA = yp;
		
		xp += Math.round(Math.random() * stepAmt) - halfStepAmt;
		yp += Math.round(Math.random() * stepAmt) - halfStepAmt;
		
		if (xp > stage.stageWidth){
			xp = stage.stageWidth - halfStepAmt;
		}else
		if (xp < 0){
			xp = halfStepAmt;
		}
		if (yp > stage.stageHeight){
			yp = stage.stageHeight - halfStepAmt;
		}else
		if (yp < 0){
			yp = halfStepAmt;
		}
		
		rxB = xp;
		ryB = yp;
		 
		lineData[dataIndex] = [rxA, ryA, rxB, ryB];        		
	    s.x = rxA;
		s.y = ryA;
		var endX:Number = rxB - rxA;
		var endY:Number = ryB - ryA;
		var m:Matrix = s.transform.matrix;
		g.clear();
		g.lineStyle(1, 0x000000, 0.3);

		g.lineTo(endX, endY);
		stage.quality = "high";
		canvas.draw(s, m);
		
		g.clear();
		g.lineStyle(3, dataIndex);
		
		g.lineTo(endX, endY);
		stage.quality = "low";
		indexCanvas.draw(s, m);
		
		dataIndex++
	}
}

I’m working on a data visualization that contains a long path made up of approximately one million points. There is some information associated with every two sets of coordinates that needs to be displayed when the user rolls their mouse over any part of the line.

I took a little time to think about the best way to do this and came up with a few techniques. The first one I tried seems to work nicely – this snippet is the proof of concept for that first technique. I tested this snippet with 1,000,000 xy coordinates and it works nicely. It takes a little while to draw though, so for the purposes of this demo I’ve just included 20,000 coordinates.

Have a look at the swf over at wonderfl.net

The way this works is by drawing lines to two different BitmapData instances. I draw anti-aliased slightly transparent lines to a BitmapData instance called “canvas” (this is added to the display list) – I then draw aliased lines to a BitmapData called “indexCanvas” (this is never added to the display list) – each aliased line uses an incremental value for its color – this incremental value is also the index for a two dimensional array containing the coordinate information for the aliased line. I use getPixel() on the “indexCanvas” and use the return value as the index for the 2D array. The data from the 2D array is used to draw a red line with the graphics class. This technique enables you to have many many rollovers and all you ever have to do is call getPixel() and use the returned color value to look up info about what you’re mouse is touching.

There are a few cool ways this could be repurposed and this is really only one solution to the problem of having many many things that you need to be able to rollover… there are others that don’t use BitmapData at all… I may write those up in the next couple of days.

Read snippet: ~20,000 Rollovers

drawTriangles() Cubes

private function addCube(xp:Number, yp:Number, zp:Number, w:Number, h:Number, leng:Number):void{
			var hw:Number = w * 0.5;
			var hh:Number = h * 0.5;
			var hl:Number = leng * 0.5;
			var xA:Number = xp - hw;
			var xB:Number = hw + xp;
			var yA:Number = yp - hh;
			var yB:Number = hh + yp;
			var zA:Number = zp - hl;
			var zB:Number = hl + zp;
        	_verts.push(xA, yA, zA,
				        xB, yA, zA,
				        xA, yB, zA,
				        xB, yB, zA,
						xA, yA, zB,
				        xB, yA, zB,
				        xA, yB, zB,
				        xB, yB, zB);
			
			var index:int = _boxIndex * 8;
			var i0:int = index, i1:int = index + 1, i2:int = index + 2;
			var i3:int = index + 3,  i4:int = index + 4, i5:int = index + 5;
			var i6:int = index + 6, i7:int = index + 7;
	        _indices.push(i0, i1, i2,
				          i1, i3, i2,
						  i6, i7, i4, 
				          i7, i5, i4, 
						  i1, i5, i3,
						  i7, i3, i5,
						  i4, i5, i0,
						  i1, i0, i5,
						  i2, i6, i0,
						  i0, i6, i4,
						  i2, i3, i6,
						  i3, i7, i6);
						  
			_faces.push(new Face(), new Face(), new Face(), 
					    new Face(),  new Face(), new Face(), 
						new Face(), new Face(), new Face(),
						new Face(), new Face(), new Face());
			_uvts.push(Math.random(), Math.random(), 0, 
					   Math.random(), Math.random(), 0, 
					   Math.random(), Math.random(), 0,
					   Math.random(), Math.random(), 0, 
					   Math.random(), Math.random(), 0, 
					   Math.random(), Math.random(), 0,
					   Math.random(), Math.random(), 0, 
					   Math.random(), Math.random(), 0);
			_boxIndex++;
		}

Lately I’ve been posting large code snippets… so today I’m highlighting part of a larger snippet – The above code is the heart of a small experiment I created this morning. It sets up a cube for use with drawTraingles().

The rest of the code can be read here:
Cubes3D.as

Have a look at the swf here…


I also put it on wonderfl…

Read snippet: drawTriangles() Cubes

Matrix Zoom and Pan

[SWF(width=600, height=600, frameRate=30)]
var sw:Number = stage.stageWidth;
var sh:Number = stage.stageHeight;

var s:Shape = Shape(addChild(new Shape()));

var scale:Number = 1;
var scaleDest:Number = 1;
var down:Boolean = false;
var dx:Number = 0, dy:Number = 0, time:Number = 0;

buttonMode = true;

addInstructions();
vectorTexture();

stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
addEventListener(Event.ENTER_FRAME, onLoop);

function addInstructions():void{
	var instruct:Sprite = Sprite(addChild(new Sprite()));
	with (instruct.graphics) beginFill(0x666666), drawRect(0,0,270, 30);
	instruct.x = instruct.y = 20;
	var txt:TextField = TextField(instruct.addChild(new TextField()));
	txt.defaultTextFormat = new TextFormat("Verdana", 11);
	txt.x = txt.y = 5;
	txt.selectable = false;
	with (txt) textColor = 0xFFFFFF, autoSize = "left", text = "Click and hold to zoom, move mouse to pan";
}

function vectorTexture():void{
	var cols:Vector.<uint> = Vector.<uint>([0xFFFFFF, 0x000000]);
	var rnd:Vector.<Number> = new Vector.<Number>(6, true);
	
	for(var i:int = 0 ; i<50; i++){
		with(s.graphics){
			lineStyle(Math.random() * 50 + 2, cols[int(Math.random()*cols.length)]);
			drawCircle(Math.random() * sw, Math.random() * sh, 10 + Math.random() * Math.random() * 400);
		}
	}
	s.graphics.lineStyle(20, 0xCCCCCC);
	s.graphics.drawRect(0, 0,sw, sh);
}

function onDown(evt:MouseEvent):void{ down = true; }
function onUp(evt:MouseEvent):void{ down = false; }
function onLoop(evt:Event):void {
   if (down){
	 scaleDest *= 1.05;  
	 time = 0;
   }else{
	 time++;
	 // zoom out after 30 iterations
	 if (time == 30){
		 scaleDest = 1;  
	 }
   }
   scale += (scaleDest - scale) / 4;
   if (scale > 10) scale = scaleDest = 10;
   
   dx += (mouseX - dx) / 4;
   dy += (mouseY - dy) / 4;
   if (dx < 0) dx = 0;
   if (dy < 0) dy = 0;
   if (dx > sw) dx = sw;
   if (dy > sh) dy = sh;
   
   // matrix zoom/pan
   var m:Matrix = s.transform.matrix;
   m.identity();
   m.translate(-dx,-dy);
   m.scale(scale, scale);
   m.translate(dx,dy);
   s.transform.matrix = m;
}

I haven’t been by the computer much these last two weeks – been traveling. Going back to nyc tomorrow so I’ll go back to posting once a day.

This snippet uses a transformation matrix to zoom in and pan a Sprite instance. For demo purposes I filled the sprite with a few circles – but you’d likely be using this with a vector image of a map, a floor plan or some other graphic that warrants zooming and panning.

Back around flash 7 (I think) before the Matrix class was introduced we used to have to use MovieClip nesting to achieve this effect.


Have a look at the swf…


Read snippet: Matrix Zoom and Pan

Fake Light w/ UV & Quads

[SWF(width = 500, height=500, backgroundColor = 0x000000)]
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;
var quadNum:int = 2200;
// standard Vectors for using drawTriangles
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number>;
var uvts:Vector.<Number> = new Vector.<Number>();
var indices:Vector.<int> = new Vector.<int>();
// needed for z-sorting
var sortedIndices:Vector.<int>;
var faces:Array = [];
// we'll use this for tranforming points
// and as the transformation matrix for our render
var m:Matrix3D = new Matrix3D();
// plot a quad
var quad:Vector.<Number>;
quad = Vector.<Number>([-10, -10, 0,
						10, -10, 0,
						-10, 10, 0,
						10, 10, 0]);
// temp vect for any transformed quads
var transQuad:Vector.<Number> = new Vector.<Number>();
var i:int;
var inc:int = 0;
for (i = 0; i<quadNum; i++){
	m.identity();
	var s:Number = (int(Math.random()*50) == 1) ? 2 + Math.random()*2 : .1 + Math.random() * 2;
	m.appendScale(s, s, 1);
	m.appendRotation(90, Vector3D.Y_AXIS);
	var mult:Number = 100 + Math.random()*200;
	m.appendTranslation(mult, 0, 0);
	m.appendRotation(Math.random()*360, Vector3D.X_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Y_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Z_AXIS);
	m.transformVectors(quad, transQuad);
	verts = verts.concat(transQuad);
	faces.push(new Vector3D());
	faces.push(new Vector3D());
	var i4:int = i * 4;
	indices.push(0 + i4, 1 + i4, 2 + i4,
				 1 + i4, 3 + i4, 2 + i4);
	mult /= 300;
	uvts.push(mult,mult,0,
			  mult+.1,mult,0,
			  mult,mult - .1,0,
			  mult + .1,mult + .1,0);
}
sortedIndices = new Vector.<int>(indices.length, true);
// create texture
var tex:BitmapData = new BitmapData(400,400,false, 0x000000);
var grad:Shape = new Shape();
var mat:Matrix = new Matrix();
mat.createGradientBox(400,400,0,0,0);
with (grad.graphics){
	beginGradientFill(GradientType.LINEAR, [0xFFFFFF,0x002244], [1, 1], [100, 255], mat);
	drawRect(0,0,400,400);
}
tex.draw(grad);
// create background
mat.createGradientBox(1600,1200,0,-550, 0);
with (grad.graphics){
	beginGradientFill(GradientType.RADIAL, [0x000000, 0x001133], [1, 1], [0, 255], mat);
	drawRect(0,0,500,500);
}
grad.x = -stage.stageWidth/2
grad.y = -stage.stageHeight/2;
addChild(grad);
// triangles will be drawn to this
var render:Shape = Shape(addChild(new Shape()));
// fix all vector lengths
verts.fixed = true, uvts.fixed = true, indices.fixed = true
pVerts = new Vector.<Number>(verts.length/3 * 2, true);
// we need these if we want perspective
var persp:PerspectiveProjection = new PerspectiveProjection();
persp.fieldOfView = 45;
// projection matrix
var proj:Matrix3D = persp.toMatrix3D();
var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	dx += (mouseX - dx) / 4;
	dy += (mouseY - dy) / 4;
	m.identity();
	m.appendRotation(dy, Vector3D.X_AXIS);
	m.appendRotation(dx, Vector3D.Y_AXIS);
	m.appendTranslation(0,0,800);
	m.append(proj);
	Utils3D.projectVectors(m, verts, pVerts, uvts);
	var face:Vector3D;
	inc = 0;
	for (var i:int = 0; i<indices.length; i+=3){
		face = faces[inc];
		face.x = indices[i];
		face.y = indices[int(i + 1)];
		face.z = indices[int(i + 2)];
		var i3:int = i * 3;
		face.w = (uvts[int(face.x*3 + 2)] + uvts[int(face.y*3 + 2)] + uvts[int(face.z*3 + 2)]) * 0.333333;
		inc++;
	}
	faces.sortOn("w", Array.NUMERIC);
	inc = 0;
	for each (face in faces){
		sortedIndices[inc++] = face.x;
		sortedIndices[inc++] = face.y;
		sortedIndices[inc++] = face.z;
	}
	render.graphics.clear();
	render.graphics.beginBitmapFill(tex, null, false, false);
	render.graphics.drawTriangles(pVerts, sortedIndices, uvts, TriangleCulling.NEGATIVE);
}

Expanding again on the z-sorting demos from the last few days – this snippet uses UV coords and a gradient to create something that vaguely resembles a light. Unlike the previous demos, the 3D cluster in this snippet is made up of quads – requiring a slight adjustment to the depth calculation.


Have a look at the swf…

I also posted the code over at wonderfl.net…

Read snippet: Fake Light w/ UV & Quads

More z-sorting

[SWF(width = 500, height=500, backgroundColor = 0x333333)]
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;


var polyNum:int = 3000;
// standard Vectors for using drawTriangles
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number>;
var uvts:Vector.<Number> = new Vector.<Number>();
var indices:Vector.<int> = new Vector.<int>();
// needed for z-sorting
var sortedIndices:Vector.<int>;
var faces:Array = [];

// we'll use this for tranforming points
// and as the transormation matrix for our render
var m:Matrix3D = new Matrix3D();

// plot a poly
var poly:Vector.<Number>;
poly = Vector.<Number>([ 0, 0, 0,
					    10, 0, 0,
					    0,10, 0]);

// temp vect for any transformed polygons
var transPoly:Vector.<Number> = new Vector.<Number>();

var i:int;
var inc:int = 0;
for (i = 0; i<polyNum; i++){
	m.identity();
	var s:Number = (int(Math.random()*50) == 1) ? 4 + Math.random()*2 : 1 + Math.random() * 2;
	m.appendScale(s, s, 1);
	m.appendRotation(Math.random()*360, Vector3D.X_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Y_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Z_AXIS);
	m.appendTranslation(200,0,0);
						 
	m.appendRotation(Math.random()*360, Vector3D.X_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Y_AXIS);
	m.appendRotation(Math.random()*360, Vector3D.Z_AXIS);
	
	m.transformVectors(poly, transPoly);
	
	verts = verts.concat(transPoly);
	faces.push(new Vector3D());
	indices.push(inc++, inc++, inc++);
	uvts.push(Math.random(), Math.random(), 0, Math.random(), Math.random(), 0, Math.random(), Math.random(), 0);
}

sortedIndices = new Vector.<int>(indices.length, true);

// create texture
var tex:BitmapData = new BitmapData(400,400,false, 0x000000);
var grad:Shape = new Shape();
var mat:Matrix = new Matrix();
mat.createGradientBox(400,400,0,0,0);
with (grad.graphics){
	beginGradientFill(GradientType.LINEAR, [0x000000, 0xAA0000, 0xFFFF00], [1, 1, 1], [20, 200, 255], mat);
	drawRect(0,0,400,400);
}
tex.draw(grad);

// create background
mat.createGradientBox(1600,1000,0,-550, -100);
with (grad.graphics){
	beginGradientFill(GradientType.RADIAL, [0x333333, 0xffffff], [1, 1], [0, 255], mat);
	drawRect(0,0,500,500);
}
grad.x = -stage.stageWidth/2
grad.y = -stage.stageHeight/2;
addChild(grad);

// triangles will be drawn to this
var render:Shape = Shape(addChild(new Shape()));

// fix all vector lengths
verts.fixed = true, uvts.fixed = true, indices.fixed = true
pVerts = new Vector.<Number>(verts.length/3 * 2, true); 

// we need these if we want perspective
var persp:PerspectiveProjection = new PerspectiveProjection();
persp.fieldOfView = 45;
// projection matrix
var proj:Matrix3D = persp.toMatrix3D();

var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	dx += (mouseX - dx) / 4;
	dy += (mouseY - dy) / 4;
	m.identity();
	m.appendRotation(dy, Vector3D.X_AXIS);
	m.appendRotation(dx, Vector3D.Y_AXIS);
	// push everything back so its not to close
	m.appendTranslation(0,0,800);
	// append the projection matrix at the end
	m.append(proj);
	
	Utils3D.projectVectors(m, verts, pVerts, uvts);
	
	var face:Vector3D;
	inc = 0;
	for (var i:int = 0; i<indices.length; i+=3){
		face = faces[inc];
		face.x = indices[i];
		// it may look odd, but casting to an int 
		// when doing operations inside array sytnax
		// adds a big speed boost
		face.y = indices[int(i + 1)];
		face.z = indices[int(i + 2)];
		var i3:int = i * 3;
		// get the average z position (t value) and store it in the Vector3D w property
		// depending on your model, you may not need to do an average of all 3 values
		face.w = (uvts[int(i3 + 2)] + uvts[int(i3 + 5)] + uvts[int(i3 + 8)]) * 0.333333;
		inc++;
	}
	 
	// sort on w, so far this beats all other sorting methods for speed,
	// faster than Vector.sort(), faster than any custom sort method I could find
	faces.sortOn("w", Array.NUMERIC);

	// re-order indices so that faces are drawn in the correct order (back to front);
	inc = 0;
	for each (face in faces){
		sortedIndices[inc++] = face.x;
		sortedIndices[inc++] = face.y;
		sortedIndices[inc++] = face.z;
	}
	
	render.graphics.clear();
	render.graphics.beginBitmapFill(tex, null, false, false);
	render.graphics.drawTriangles(pVerts, sortedIndices, uvts, TriangleCulling.NONE);
}

This is a slightly more advanced version of the z-sorting demo from yesterday. Here 3000 polygons are randomly arranged in a sphere formation…


Have a look at the swf…

Read snippet: More z-sorting

drawTriangles() & z-sorting

[SWF(width = 500, height=500, backgroundColor = 0x000000)]
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;

// standard Vectors for using drawTriangles and projectVectors
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number>;
var uvts:Vector.<Number>;
var indices:Vector.<int>;
// needed for z-sorting
var sortedIndices:Vector.<int>;
var faces:Array = [];

// we'll use this for transforming points
// and as the transformation matrix for our render
var m:Matrix3D = new Matrix3D();

// plot a poly
var poly:Vector.<Number>;
poly = Vector.<Number>([ 0, 0, 0,
					    10, 0, 0,
					    0,10, 0]);

verts = verts.concat(poly);
faces.push(new Vector3D());

// add two more polygons by transorming the poly Vector
// and concatenating it to the verts Vector
// Vector3D instances are added to the faces
// Array for z-sorting

// temp vect for any transformed polygons
var transPoly:Vector.<Number> = new Vector.<Number>();

m.appendRotation(10, Vector3D.Z_AXIS);
m.appendTranslation(0,-2,5);
m.transformVectors(poly, transPoly);

verts = verts.concat(transPoly);
faces.push(new Vector3D());

m.appendRotation(10, Vector3D.Z_AXIS);
m.appendTranslation(0,-2,5);
m.transformVectors(poly, transPoly);
verts = verts.concat(transPoly);
faces.push(new Vector3D());

// hard coded indices
indices = Vector.<int>([0, 1, 2, 3, 4, 5, 6, 7, 8]);
sortedIndices = new Vector.<int>(indices.length, true);

// create texture
var tex:BitmapData = new BitmapData(100,100,false, 0x000000);
tex.fillRect(new Rectangle(0,0,50,50), 0xFF0000);
tex.fillRect(new Rectangle(50,0,50,50), 0x0000FF);
tex.fillRect(new Rectangle(0,50,50,50), 0x00FF00);

// hard coded uvts 
uvts = Vector.<Number>([0,0,0, .5,0,0, 0,.5,0, 
						.53, 0, 0, 1, 0, 0, .53, .5, 0,
						 0,.6,.5, 0,.6,0, 0,1, 0]);
						
// fix all vector lengths
verts.fixed = true, uvts.fixed = true, indices.fixed = true
pVerts = new Vector.<Number>(verts.length/3 * 2, true); 

// we need these if we want perspective
var persp:PerspectiveProjection = new PerspectiveProjection();
// projection matrix
var proj:Matrix3D = persp.toMatrix3D();

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	m.identity();
	m.appendRotation(mouseY * 2, Vector3D.X_AXIS);
	m.appendRotation(mouseX * 2, Vector3D.Y_AXIS);
	// push everything back so its not too close
	m.appendTranslation(0,0,40);
	// append the projection matrix at the end
	m.append(proj);
	
	Utils3D.projectVectors(m, verts, pVerts, uvts);
	
	var face:Vector3D;
	var inc:int = 0;
	for (var i:int = 0; i<indices.length; i+=3){
		face = faces[inc];
		face.x = indices[i];
		// it may look odd, but casting to an int 
		// when doing operations inside array sytnax
		// adds a big speed boost
		face.y = indices[int(i + 1)];
		face.z = indices[int(i + 2)];
		var i3:int = i * 3;
		// get the average z position (t value) and store it in the Vector3D w property
		// depending on your model, you may not need to do an average of all 3 values
                // (t is the distance from the eye to the texture)
		face.w = (uvts[int(i3 + 2)] + uvts[int(i3 + 5)] + uvts[int(i3 + 8)]) * 0.333333;
		inc++;
	}
	
	// sort on w, so far this beats all other sorting methods for speed,
	// faster than Vector.sort(), faster than any custom sort method I could find
	faces.sortOn("w", Array.NUMERIC);
	
	// re-order indices so that faces are drawn in the correct order (back to front);
	inc = 0;
	for each (face in faces){
		sortedIndices[inc++] = face.x;
		sortedIndices[inc++] = face.y;
		sortedIndices[inc++] = face.z;
	}
	
	graphics.clear();
	graphics.beginBitmapFill(tex, null, false, false);
	graphics.drawTriangles(pVerts, sortedIndices, uvts, TriangleCulling.NONE);
}

So you want to be able to do some z-sorting with drawTriangles()? Well, its extremely unintuitive. Here is what you need to know:

1) Vector.sort() is slow
2) Array.sortOn() is quite fast
3) I couldn’t get any custom sorting method to be faster than Array.sortOn
4) You can use the t value from uvts to do z-sorting (like in this demo)
5) If your going for speed, don’t forget to use fixed Vectors (I often forget this step)
6) When working with Vectors cast any operations inside brackets to int() (my tests showed this is a huge speed boost up to 3x faster – franky I think it’s horrible that you have to do this).

The swf is not very interesting because I wanted to keep it super simple, but here it is anyway…


Questions

I was told and have read that drawTriangles is slower than using drawGraphicsData and a GraphicsTrianglePath instance. I tested this extensively and found that drawGraphicsData was slower. I’m still not sure which is faster but am up for checking out any simple benchmarks that people have.

drawTriangles is supposed to be faster without adding t values to the uvts Vector. In my benchmark tests there was no real difference in speed. The t value is used to render more accurate textures – which would mean you could potentially use less triangles in your models. One would assume that not using a t value would be faster… but I couldn’t confirm this. Again if someone has a good benchmark for this, please let me know.

Help

I had a great deal of help from a few people on Twitter, Katopz (Away3D contributor) of sleepydesign.com made me aware of the fact that Array.sortOn is the way to go… You can see some great demos over at Katopz’s blog. While I didn’t end up using a custom sorting method, Inspirit
pointed me to his article about custom Vector sorting methods which proved to be very enlightening. I was able to get some really great results for doing different types of sorting – just sorting 1D Vectors with FlashSort can be very fast (faster than Array.sortOn – but not helpful for sorting a 1D Vector of indices).

I also learned a good deal by looking at this code post by Psyark… I actually optimized that code to run about 2x faster (will post that on wonderfl.net at some point, it just needs to be cleaned up).

kevinSuttle sent me a link to The video

Read snippet: drawTriangles() & z-sorting

Spring PerspectiveProjection

var pointNum:int = 3000;
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;

var verts:Vector.<Number>  = new Vector.<Number>();
var tVerts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uv:Vector.<Number> = new Vector.<Number>();
var cmds:Vector.<int> = new Vector.<int>();

var index:int = 0;
var half:Number = pointNum / 20000;
for (var i:int = 0; i<pointNum; i+=3){
	verts[i] = 0.08 * Math.cos(i * Math.PI / 180);
	verts[i+1] = 0.08 * Math.sin(i * Math.PI / 180);
	verts[i+2] =  i / 10000 - half;
	cmds[index++] = 2;
}
cmds[0] = 1;

var proj:PerspectiveProjection = new PerspectiveProjection();
proj.fieldOfView = 45;
var projMat:Matrix3D = proj.toMatrix3D();
var m:Matrix3D = new Matrix3D();
var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
       m.identity();
	   dx += (mouseX - dx) / 4;
	   dy += (mouseY - dy) / 4;
	   m.appendRotation(dy,Vector3D.X_AXIS);
	   m.appendRotation(dx,Vector3D.Y_AXIS);
	   m.appendTranslation(0,0,0.5);
	   m.transformVectors(verts, tVerts);
	   Utils3D.projectVectors(projMat, tVerts, pVerts, uv);
	   graphics.clear();
	   graphics.lineStyle(3,0x000000);
	   graphics.drawPath(cmds, pVerts);
}

This snippet draws a spring shape in 3D with perspective. This is the first snippet where I’ve made use of the PerspectiveProjection class. So if your wondering how to add perspective to your Utils3D.projectVectors code… this is one way to do it…


Have a look at the swf…

Read snippet: Spring PerspectiveProjection

Quick Pixel Sphere

var pointNum:int = 20000;
var radius:int = 150;

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));
var verts:Vector.<Number>  = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var uv:Vector.<Number> = new Vector.<Number>();

for (var i:int = 0; i<pointNum; i+=3){
	var xp:Number = Math.random() * 400 - 200;
	var yp:Number = Math.random() * 400 - 200;
	var zp:Number = Math.random() * 400 - 200;
	var dist:Number = Math.sqrt(xp * xp + yp * yp + zp * zp);
	// normalize and scale x,y,z 
	verts[i] = xp / dist * radius;
	verts[i+1] = yp / dist * radius;
	verts[i+2] = zp / dist * radius;
}

var m:Matrix3D = new Matrix3D();
var dx:Number = 0, dy:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
       m.identity();
	   dx += (mouseX - dx) / 4;
	   dy += (mouseY - dy) / 4;
	   m.appendRotation(dx, Vector3D.X_AXIS);
	   m.appendRotation(dy, Vector3D.Y_AXIS);
	   m.appendTranslation(200,200,0);
	   Utils3D.projectVectors(m, verts, pVerts, uv);
	   canvas.fillRect(canvas.rect, 0x000000);
	   for (var i:int = 0; i<pVerts.length; i+=2){
	     canvas.setPixel(pVerts[i], pVerts[i + 1], 0xFFFFFF);
	   }
}

This snippet shows a quick way to randomly place a bunch of xyz coordinates on the surface of a sphere. I saw this trick in an OpenGL book a few years back – dug around my books but couldn’t find it… If I find it I’ll update this post.

The trick is achieved by normalizing the vector defined by each 3D coordinate…


Have a look at the swf…

Read snippet: Quick Pixel Sphere

Another Matrix.transformPoint()

[SWF(width = 628, height=500)]
var trans:Matrix = new Matrix();
var pnt:Point = new Point();
x = stage.stageWidth / 2;
y = stage.stageHeight / 2;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	graphics.clear();
	graphics.lineStyle(10, 0x000000, 1, false, LineScaleMode.NORMAL, CapsStyle.SQUARE);
	pnt.x = 0;
	pnt.y = 0;
	trans.identity();
	trans.translate(15,15);
	trans.rotate(mouseX/10 * Math.PI / 180);
	graphics.moveTo(pnt.x, pnt.y);
	for (var i:int = 0; i<12; i++){
		pnt = trans.transformPoint(pnt);
		graphics.lineTo(pnt.x, pnt.y);
	}
}

I was thinking about processing and OpenGL today… I always really enjoyed using matrix stuff, working with the matrix stack, using push() and pop() etc… Understanding how to use matrices is pretty important when your doing advanced graphics in actionscript. If you haven’t messed with matrices, this snippet is a good place to start. It uses Matrix.transformPoint() to draw a series of connected lines that are controlled by the x location of the mouse. Back before flash 8, this kind of thing was usually done using trig or MovieClip nesting…

I posted another snippet on this topic awhile back.

Read snippet: Another Matrix.transformPoint()