## Thursday, November 10, 2011

### writing a 3d engine

This is based around a lingo tutorial I read a while ago by some guy from New Zealand, he wrote a simple 3d engine (in later versions of director a 3d engine was incorporated anyway, this was before that)… I've been looking up the tutorial on google, but it seems to have disappeared, a pity because it would explain the concept around which 3d is based in more depth. Anyway, from the original I took onboard the principals and translated the lingo into actionscript 2.0.

It would seem Flash is about to die too, so someday I'll have to re-write this in javascript.

Here is the actionscript, the important part is the cal2d bit:

_root.onLoad = function() {
corNers = 8;
faCes = 6;
for (i=0; i _root.createEmptyMovieClip("fa0"+i, i);
}
vFov = 180;
xOff = Stage.height/2;
yOff = Stage.height/2;
zPos = new Array();
xyzP = new Array( { x: -50, y: 50, z:-50 },
{ x: 50, y: 50, z:-50 },
{ x: -50, y:-50, z:-50 },
{ x: 50, y:-50, z:-50 },
{ x: -50, y: 50, z: 50 },
{ x: 50, y: 50, z: 50 },
{ x: -50, y:-50, z: 50 },
{ x: 50, y:-50, z: 50 } );
vCon = new Array( 0, 1, 2, 3,
4, 5, 6, 7,
0, 1, 4, 5,
2, 3, 6, 7,
0, 2, 4, 6,
1, 3, 5, 7 );
coL = new Array( 0x6600FF,
0x00FFFF,
0x00FF00,
0xFFFF00,
0xFF0000,
0xFF00FF );
opA = new Array( 85, 95, 85, 95, 90, 65 );
};
function Entry(index, value) {
this.index = index;
this.value = value;
}
function sortValues(a, b) {
return ((a.value>b.value) ? -1 : ((a.value}
_root.onEnterFrame = function() {
cal2d();
// updateAfterEvent()// if mouseMove;
};
function cal2d() {
xRot -= (_ymouse-xOff)/2000;
yRot += ((_xmouse)-yOff)/2000;// and with it's y axis
mCYr = Math.cos(yRot);
mSYr = Math.sin(yRot);
mCXr = Math.cos(xRot);
mSXr = Math.sin(xRot);
for (i=0; i tmpZpos = (xyzP[i].z*mCYr)-(xyzP[i].x*mSYr);
tmpX = (xyzP[i].z*mSYr)+(xyzP[i].x*mCYr);
tmpZ = (xyzP[i].y*mSXr)+(tmpZpos*mCXr);
tmpY = (xyzP[i].y*mCXr)-(tmpZpos*mSXr);
eSca = 1/(tmpZ/vFov+1);
_root["x0"+i] = tmpX*eSca+xOFF;
_root["y0"+i] = tmpY*eSca+yOFF;
_root["z0"+i] = tmpZ// Z positions needed for sorting the z order of the faces
}
for (i=0; i e = i*4;
// pCal = z position of center of each face
pCal = (_root["z0"+vCon[e]]+_root["z0"+vCon[e+1]]+_root["z0"+vCon[e+2]]+_root["z0"+vCon[e+3]])/4;
zPos[i] = new Entry(i, pCal);// begin the z ordering of faces
}
zPos.sort(sortValues);
for (i=0; i e = i*4;
z = zPos[i].index;
_root["fa0"+z].swapDepths(i);// z order the faces on the stage
with (_root["fa0"+i]) {
clear();
lineStyle(0, 0x000000, 50);
beginFill(_root.coL[i], opA[i]);
moveTo(_root["x0"+vCon[e]], _root["y0"+vCon[e]]);
lineTo(_root["x0"+vCon[e+1]], _root["y0"+vCon[e+1]]);
lineTo(_root["x0"+vCon[e+3]], _root["y0"+vCon[e+3]]);
lineTo(_root["x0"+vCon[e+2]], _root["y0"+vCon[e+2]]);
lineTo(_root["x0"+vCon[e]], _root["y0"+vCon[e]]);
endFill();

}
}
}