Esempio n. 1
0
    MeshData CreateMesh(Vector3 origin)
    {
        int trianglesPerCube = 4 * 3;

        Vector3[] vertices  = new Vector3[width * length * height * 12];
        Color32[] colors    = new Color32[vertices.Length];
        int[]     triangles = new int[width * length * height * trianglesPerCube];

        int cube            = 0;
        int currentTriangle = 0;

        for (int y = 0; y < height; y++)
        {
            for (int z = 0; z < length; z++)
            {
                for (int x = 0; x < width; x++, cube++)
                {
                    Vector3 cubeOrigin   = origin + new Vector3(x, y, z);
                    int     vertexOffset = cube * 12;

                    Vector3[] cubeVertices = CreateCubeVertices(cubeOrigin);
                    Triangulation.CubePoint[] cubePoints = new Triangulation.CubePoint[8];
                    for (int i = 0; i < 8; i++)
                    {
                        Vector3 vertex   = cubeVertices[i];
                        float   isoValue = CalculateIsoValue(vertex);
                        cubePoints[i] = new Triangulation.CubePoint(vertex, isoValue);
                    }

                    int cubeIndex = Triangulation.CalculateCubeIndex(isoLevel, cubePoints);

                    /* Cube is entirely in/out of the surface */
                    if (Triangulation.IsTrivial(cubeIndex))
                    {
                        continue;
                    }

                    Vector3[] interpolatedVertices = Triangulation.GetVertices(isoLevel, cubeIndex, cubePoints);
                    for (int v = 0; v < interpolatedVertices.Length; v++)
                    {
                        colors[vertexOffset + v]   = CalculateColor(interpolatedVertices[v].y / height);
                        vertices[vertexOffset + v] = interpolatedVertices[v];
                    }

                    int[] interpolatedTriangles = Triangulation.GetTriangles(cubeIndex);
                    for (int t = 0; t < interpolatedTriangles.Length; t++)
                    {
                        triangles[currentTriangle + t] = interpolatedTriangles[t] + vertexOffset;
                    }
                    currentTriangle += interpolatedTriangles.Length;
                }
            }
        }
        return(new MeshData(vertices, colors, triangles));
    }