Utils3D.projectVectors() Lathe

[SWF(width = 500, height = 500, backgroundColor = 0x000000)]
var halfWidth:Number = stage.stageWidth / 2;
var halfHeight:Number = stage.stageHeight / 2;
var loc:Vector.<Number>;

graphics.lineStyle(0, 0xFF0000);
graphics.moveTo(halfWidth, 0);
graphics.lineTo(halfWidth, stage.stageHeight);
graphics.moveTo(0, halfHeight);
graphics.lineTo(stage.stageWidth, halfHeight);

var line:Shape = Shape(addChild(new Shape()));
line.x = halfWidth;

var idle:Function = function(){};
var currentMode:Function = idle;
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
addEventListener(Event.ENTER_FRAME, onLoop);
function onDown(evt:MouseEvent):void{
	if (contains(frame)){
		removeChild(frame);
		currentMode = idle;
		line.graphics.clear();
		return;
	}
	loc = new Vector.<Number>();
	line.graphics.lineStyle(0,0xFFFFFF);
	line.x = halfWidth
	line.y = halfHeight;
	line.graphics.moveTo(line.mouseX, line.mouseY);
	currentMode = captureLocs;
	canvas.fillRect(canvas.rect, 0x000000);
}
function onUp(evt:MouseEvent):void{
	if (currentMode == idle) return;
	setupLathe();
	currentMode = showLathe;
}

function onLoop(evt:Event):void{
	currentMode();
}
function captureLocs():void{
	loc.push(line.mouseX);
	loc.push(line.mouseY);
	loc.push(0);
	line.graphics.lineTo(line.mouseX, line.mouseY);
}
/**
 -- Lathe Stuff:
*/
var canvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight,false, 0x000000);
var frame:Bitmap = new Bitmap(canvas);
var dx:Number=0;
var dy:Number=0;
 var matrix:Matrix3D = new Matrix3D();
var pVerts:Vector.<Number>;
var uvts:Vector.<Number>;
function setupLathe():void{
	addChild(frame);
	pVerts =  new Vector.<Number>();
	uvts = new Vector.<Number>();
	var nVerts:Vector.<Number> = new Vector.<Number>();
	var tVerts:Vector.<Number> = new Vector.<Number>();
	matrix.identity();
	var step:Number = 2;
	for (var i:int = 0; i <360; i+=step){
		matrix.appendRotation(step,Vector3D.Y_AXIS);
		matrix.transformVectors(loc, tVerts);
		nVerts = nVerts.concat(tVerts);
	}
	loc = nVerts.concat();
}
function showLathe():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(halfWidth, halfHeight, 0);
	Utils3D.projectVectors(matrix, loc, pVerts, uvts);
	canvas.lock();
	canvas.fillRect(canvas.rect, 0x000000);
	var leng:int = pVerts.length;
	for (var i:int = 0; i<leng; i+=2){
		canvas.setPixel( pVerts[i], pVerts[i + 1], 0xFFFFFF);
	}
	canvas.unlock();
}

This snippet allows you to create 3D lathe shapes by drawing a 2D line. This is done using Utils3D.projectVectors() and Matrix.transformVectors().

Have a look at the swf here…

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *