GLSL 3D Fractals - Menger Sponge
The Menger Sponge is the 3D generalization of the Sierpinski carpet, discovered by Karl Menger in 1926. It's a fascinating geometric fractal with paradoxical properties: infinite surface area yet zero volume, making it a perfect example of a fractal dimension between 2 and 3.
Interactive Demo
Move your mouse to rotate the camera and explore the infinite detail. Scroll to adjust the iteration count and see how the structure becomes more complex:
Mathematical Foundation
Construction Process
The Menger Sponge is constructed recursively:
- Start: A cube
- Divide: Split into 3×3×3 = 27 smaller cubes
- Remove: Remove the center cube and the 6 face-center cubes (7 total)
- Repeat: Apply the same process to the remaining 20 cubes
- Infinite: Continue ad infinitum
Distance Estimation
We use a fold-based approach for efficient computation:
float mengerSpongeDE(vec3 pos, int iterations) {
vec3 p = pos;
float scale = 1.0;
for (int i = 0; i < iterations; i++) {
// Fold into first octant
p = abs(p);
// Scale by 3
p *= 3.0;
scale *= 3.0;
// Remove center boxes
if (p.x > 1.0 && p.y > 1.0) p.xy = vec2(2.0) - p.xy;
if (p.x > 1.0 && p.z > 1.0) p.xz = vec2(2.0) - p.xz;
if (p.y > 1.0 && p.z > 1.0) p.yz = vec2(2.0) - p.yz;
p -= 1.0;
}
return sdBox(p, vec3(0.5)) / scale;
}
Fractal Dimension
The Menger Sponge has a fractal dimension of:
This is between 2 (surface) and 3 (volume), reflecting its paradoxical nature. The dimension is calculated using the scaling factor (3) and the number of copies (20) that remain after each iteration.
Properties
- Infinite surface area: Each iteration multiplies the surface area
- Zero volume: The removed cubes eventually remove all volume
- Self-similarity: Every part looks like the whole
- Hausdorff dimension: Approximately 2.727
Visual Characteristics
- Geometric precision: Sharp edges and corners
- Infinite detail: Zooming in reveals the same pattern
- Symmetry: Cubic symmetry in all three axes
- Complexity: Each iteration adds 20× more detail
Optimization
The fold-based approach is highly efficient:
- No recursion: Iterative algorithm
- Fast convergence: Distance estimate is accurate
- GPU-friendly: Parallelizable per pixel
Applications
- Mathematical visualization: Teaching fractal geometry
- Architectural inspiration: Self-similar structures
- Game environments: Procedural geometric worlds
- Art: Geometric abstract art
References
- Menger Sponge on Wikipedia
- "Fractal Geometry of Nature" by Benoit Mandelbrot
- Inigo Quilez - Distance Functions
Related Articles
- GLSL 3D Fractals - Sierpinski Tetrahedron - Related geometric fractal
- GLSL 3D Fractals Series Index - Return to series index