06 Jul 2023

The Menger Sponge in Unity

I created a Menger sponge generator in Unity. A Menger sponge is a fractal curve. The steps to create one go like this.

Start with a single cube
for i = 0 to L do
     for each cube do
          Subdivide cube into 27 subcubes of one third the side length
          Delete the 7 inner subcubes (see figure, second from the left).
     end for
end for

(From UT Austin’s project website)

For my code, instead of subdividing one cube, I used recursion to create 27 smaller cubes in the place of each cube. I then remove the 7 cubes I need to and recursively pass the coordinates of the 20 cubes into the function that creates the sponge.

void Sponge(int depth,
            float cx, float cy, float cz, float size, int iter = 0) {

    List<List<float>> coords = new List<List<float>>();

    if (depth == 0) {
        AddCube(cx, cy, cz, size * 3);
        Debug.Log(size);
    }

    else {
        iter += 1;
        
        // center row
        coords.Add(new List<float>() {cx + size, cy + size, cz});
        coords.Add(new List<float>() {cx + size, cy - size, cz});
        coords.Add(new List<float>() {cx - size, cy + size, cz});
        coords.Add(new List<float>() {cx - size, cy - size, cz});

        // right row
        coords.Add(new List<float>() {cx + size, cy + size, cz + size});
        coords.Add(new List<float>() {cx - size, cy + size, cz + size});
        coords.Add(new List<float>() {cx + size, cy - size, cz + size});
        coords.Add(new List<float>() {cx - size, cy - size, cz + size});

        // left row
        coords.Add(new List<float>() {cx + size, cy + size, cz - size});
        coords.Add(new List<float>() {cx + size, cy - size, cz - size});
        coords.Add(new List<float>() {cx - size, cy + size, cz - size});
        coords.Add(new List<float>() {cx - size, cy - size, cz - size});

        // middle row 1
        coords.Add(new List<float>() {cx, cy + size, cz + size});
        coords.Add(new List<float>() {cx, cy + size, cz - size});
        coords.Add(new List<float>() {cx, cy - size, cz + size});
        coords.Add(new List<float>() {cx, cy - size, cz - size});

        // middle row 2
        coords.Add(new List<float>() {cx + size, cy, cz + size});
        coords.Add(new List<float>() {cx + size, cy, cz - size});
        coords.Add(new List<float>() {cx - size, cy, cz + size});
        coords.Add(new List<float>() {cx - size, cy, cz - size});

        for (int i = 0; i < coords.Count; i++) {
            float x = coords[i][0];
            float y = coords[i][1];
            float z = coords[i][2];
            Sponge(depth - 1, x, y, z, size / 3, iter);
        }

    }
}

The Result

Here’s the result:

That’s all for now.

Code here. Here’s the assignment from UT Austin which formed the basis for my code.