private static void SortPolygons(ObjectFace[] List, int ListCount, double[] ListDistance, int ListOffset, double TimeElapsed)
{
// calculate distance
double cx = World.AbsoluteCameraPosition.X;
double cy = World.AbsoluteCameraPosition.Y;
double cz = World.AbsoluteCameraPosition.Z;
for (int i = 0; i < ListCount; i++)
{
int o = List[i].ObjectIndex;
int f = List[i].FaceIndex;
if (ObjectManager.Objects[o].Mesh.Faces[f].Vertices.Length >= 3)
{
int v0 = ObjectManager.Objects[o].Mesh.Faces[f].Vertices[0].Index;
int v1 = ObjectManager.Objects[o].Mesh.Faces[f].Vertices[1].Index;
int v2 = ObjectManager.Objects[o].Mesh.Faces[f].Vertices[2].Index;
double v0x = ObjectManager.Objects[o].Mesh.Vertices[v0].Coordinates.X;
double v0y = ObjectManager.Objects[o].Mesh.Vertices[v0].Coordinates.Y;
double v0z = ObjectManager.Objects[o].Mesh.Vertices[v0].Coordinates.Z;
double v1x = ObjectManager.Objects[o].Mesh.Vertices[v1].Coordinates.X;
double v1y = ObjectManager.Objects[o].Mesh.Vertices[v1].Coordinates.Y;
double v1z = ObjectManager.Objects[o].Mesh.Vertices[v1].Coordinates.Z;
double v2x = ObjectManager.Objects[o].Mesh.Vertices[v2].Coordinates.X;
double v2y = ObjectManager.Objects[o].Mesh.Vertices[v2].Coordinates.Y;
double v2z = ObjectManager.Objects[o].Mesh.Vertices[v2].Coordinates.Z;
double w1x = v1x - v0x, w1y = v1y - v0y, w1z = v1z - v0z;
double w2x = v2x - v0x, w2y = v2y - v0y, w2z = v2z - v0z;
double dx = -w1z * w2y + w1y * w2z;
double dy = w1z * w2x - w1x * w2z;
double dz = -w1y * w2x + w1x * w2y;
double t = dx * dx + dy * dy + dz * dz;
if (t != 0.0)
{
t = 1.0 / Math.Sqrt(t);
dx *= t; dy *= t; dz *= t;
double w0x = v0x - cx, w0y = v0y - cy, w0z = v0z - cz;
t = dx * w0x + dy * w0y + dz * w0z;
ListDistance[i] = -t * t;
}
}
}
// sort
Array.Sort<double, ObjectFace>(ListDistance, List, 0, ListCount);
// update object list
for (int i = 0; i < ListCount; i++)
{
ObjectList[List[i].ObjectListIndex].FaceListIndices[List[i].FaceIndex] = (i << 2) + ListOffset;
}
}