There are already several 3D Engines for Flash, including PaperVision3D, Away3D and Sandy. All these engines have started at first with ActionScript 2 as the main language, and have then evolved when Flash9 was released with AS3 language.
One of the biggest problem with 3D-in-Flash was perspective correction. This is because Flash is a 2D vector engine, which doesn't know about 3D. And when you need to display some triangles which are mapped with a bitmap textured, you need to deform your texture.
Flash allows bitmap deformations, but only affine ones (using a 2x3 Matrix). This is enough for translation, rotation and scaling, but cannot "bend" a bitmap to make it look like it's being put into perspective.
All the 3D Flash engines have then to dynamically create additional triangles, in order to split the rendering into several small triangles that are correcting the texture perspective. It works, but it requires a lot of CPU for creating the triangles, and in the end require more triangles to be drawn by Flash, which also uses CPU...
... that was until Flash Player 10 was released !
In case you missed it, the new
Graphics.drawTriangles API allows you to draw textured triangles, using not only UV coordinates, but UVW coordinates (W being 1/Z).
With this tool in hands, the complexity of writing a Flash 3D engine greatly decreased, so I wanted to give it a try. Not that I want to compete with other 3D engines, but I like to discover things by myself, and writing it from scratch is the best way to learn.
Here's some small result :
- you can move the camera around using the mouse
- you can zoom using the up/down arrows
Wto change to Wire-Mode
Pto change to Vertex-Color Material : in that mode, lights are not only impacting the illumination of the object, but also the color of each vertex.
A few notes for people interested in technical details :
- the scene consists in ~2000 triangles, most of them used by the sphere
- there are 2 Point-Lights and no directional lights, all calculated in realtime
- default mode uses Gouraud shading. Flat shading is also supported
- the VertexColor shading mode works together with the VColor material, which enables realtime illumination of the object
- the cube uses a texture + a color material, the sphere and the other object are using a simple color material
- since we need several passes for rendering complex materials, backface culling is performed before sending triangles to
- triangles are sorted in realtime using the Painter's algorithm
- most of the time is spent in letting Flash draw triangles. Performances are actually a lot better on Firefox than on IE7 (not sure why)
The engine is still in progress consists in around 2000 lines of Haxe code, to be released as open source later. Using Haxe features such as FastList, "inline" methods and integer optimizations really helped to bring the speed it its best.
EDIT : the sources are available on http://code.google.com/p/haxe3d