AS3: 3D sorting; getRelativeMatrix3D not working?
===

This might be quite hard to understand.

I'm making a custom 3D engine with just a few features - just sorting the triangles by Z, drawing them with the `Graphics` of the stage, then render the scene with `BitmapData`. And I'm already having problems with the sorting.

The "base" - which here is `stage`, is the `DisplayObjectContainer` that is supposed to be the "father" of all triangles.

All the information of the triangles is stored in an array, in my code, named 'objects'. And there is another empty array called 'sorted'. The elements in 'objects' are all `Object` instances, the prototype is:

    {v1:Vector3D, v2:Vector3D, v3:Vector3D, fill:uint, alpha:Number};

`v1`, `v2`, `v3` are `Vector3D` instances representing the first, second and the third vertices of the triangle. `fill` is the color the triangle is to be filled, and `alpha` is the transparency value (alpha value) of the fill of the triangle.

I create a `for` loop with the following code:

    for (var i:int = 0; i < this.objects.length; i++) {

This way I can get all the `Object` instances stored in the 'objects' array. For each element in the 'objects' array, the steps are:

 1. Calculate the average (or 'middle'?) value of the x, y, and z
    propeties of the three `Vector3D` instances. Add the maximum and
    minimum x, y, and z values and divide each results by 2. For
    example, if the three `Vector3D` instances were `new Vector3D(1, 2,
    3)`, `new Vector3D(2, 3, 4)`, and `new Vector3D(3, 4, 5)` then the
    average x, y, z will be 2, 3, 4. (which are (1+3)/2, (2+4)/2, and
    (3+5)/2. Get that?)
    
 2.  Create a new `Sprite` instance, name it 'sprite' and assign the
    three average values as its x, y, and z properties.
    
 3. Then use the `transform.getRelativeMatrix3D()` method, the parameter
    is the "base" `DisplayObjectContainer`, abovementioned, and assign
    the returned `Matrix3D` instance to a new one called 'matrix3D'.
    
 4. To the 'sorted' array, push an `Object` instance with the exact same parameters of the
    element `objects[i]`, and an additional value called 'rz',
    containing the `position.z` of 'matrix3D'.

When the loop is finished, sort the 'sorted' array according to the 'rz' values.

    this.sorted.sortOn("rz", Array.NUMERIC|Array.DESCENDING);

Then, draw the triangles in the order of triangles contained in the 'sorted' array, with another `for` loop.

When I run it, some triangles that should be behind others come in front of them, which is definitely not something I expect it. Anything wrong with the steps?

Here is my one-and-only theory:

 1. I shouldn't have assign the average (or "middle"?) values of the x, y, z properties to the `Sprite`
    instance 'sprite'.

I might be uploading the source code later.

Any idea?

Thanks! :)