Fractals and Mathematical GLSL
GLSL shaders provide a unique intersection of mathematics and visual art. By executing mathematical functions in parallel across thousands of GPU cores, we can visualize complex mathematical structures in real-time. This page explores fractals, complex dynamics, and mathematical visualization through practical GLSL examples.
Complex Numbers and Iteration
Fractals emerge from iterating mathematical functions in the complex plane. The connection between iteration, complex numbers, and visual patterns represents one of the most beautiful intersections of mathematics and graphics.
Complex Number Arithmetic in GLSL
Complex numbers are represented as 2D vectors in GLSL. A complex number z = a + bi becomes vec2(a, b). Complex multiplication follows:
// z₁ * z₂ = (a₁a₂ - b₁b₂) + (a₁b₂ + a₂b₁)i
vec2 complexMult(vec2 z1, vec2 z2) {
return vec2(
z1.x * z2.x - z1.y * z2.y, // Real part
z1.x * z2.y + z1.y * z2.x // Imaginary part
);
}
// z² = (a² - b²) + 2abi
vec2 complexSquare(vec2 z) {
return vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y);
}
Mathematical Foundation: Complex numbers extend the real numbers by adding the imaginary unit i where i² = -1. This extension enables solving equations like x² + 1 = 0 and creates rich mathematical structures. The Mandelbrot set was first visualized by Benoit Mandelbrot in 1980, building on work by Gaston Julia and Pierre Fatou from the early 20th century 1(#references).
The Mandelbrot Set
The classic Mandelbrot set is defined by the iteration z = z² + c, where both z and c are complex numbers. Points that don't escape to infinity after many iterations belong to the set. The escape criterion |z| > 2 comes from mathematical analysis: if |z| > 2, then |z²| = |z|² > 4, and the iteration will diverge 3(#references).
Key Mathematical Concepts:
- Complex Number Arithmetic: Implementing the Mandelbrot iteration
z = z² + cusing vector operations - Escape Time Algorithm: Points that escape quickly get one color, points that never escape get another
- Smooth Coloring: Using distance estimation (
log(log(|z|))) for smooth color transitions - technique popularized by Linas Vepstas 4(#references) - Dynamic Zoom: Adjusting iteration count based on zoom level - deeper zooms need more iterations to show detail 5(#references)
ShaderToy References:
- Mandelbrot Set by iq - Classic implementation with smooth coloring
- Mandelbrot Zoom by FabriceNeyret2 - Deep zoom exploration
- Mandelbrot with Distance Estimation by mla - Advanced distance estimation techniques
Julia Sets
Julia sets are related to the Mandelbrot set but fix the constant c and vary the initial point z₀. Each point in the Mandelbrot set corresponds to a Julia set, creating a beautiful duality. The Julia set visualization was pioneered by Gaston Julia in 1918 2(#references).
Mathematical Insight: Julia sets reveal the structure of the complex dynamics. Move your mouse to change the constant c and watch how the Julia set transforms. Points in the Mandelbrot set correspond to connected Julia sets, while points outside correspond to disconnected Julia sets (Cantor dust).
ShaderToy References:
- Julia Set by iq - Interactive Julia set exploration
- Julia Sets Collection by FabriceNeyret2 - Multiple Julia set variations
Burning Ship Fractal
The Burning Ship fractal is a variant that uses absolute values in the iteration: z = (|Re(z)| + i|Im(z)|)² + c. This creates dramatically different, fire-like patterns. The fractal was discovered by Michael Michelitsch and Otto E. Rössler in 1992 7(#references).
Mathematical Insight: The absolute value operation "folds" the complex plane, creating sharp edges and angular structures that resemble flames. This demonstrates how small changes to iteration formulas can produce completely different visual results 8(#references).
ShaderToy References:
- Burning Ship by iq - Classic Burning Ship implementation
- Burning Ship Variations by FabriceNeyret2 - Different Burning Ship variants
Newton Fractal
Newton fractals visualize the basins of attraction for Newton's method of finding polynomial roots. Each color represents a different root that the method converges to. The visualization was pioneered by John H. Hubbard 9(#references).
Mathematical Insight: Newton's method uses the iteration z = z - f(z)/f'(z) to find roots. The fractal shows how the starting point determines which root is found, revealing the complex boundary structure between different basins of attraction. The fractal nature of these boundaries was first rigorously analyzed in 10(#references), showing that the boundaries have infinite detail and fractal dimension.
ShaderToy References:
- Newton Fractal by iq - Newton's method visualization
- Newton Basins by FabriceNeyret2 - Different polynomial roots
Buddhabrot
The Buddhabrot is a probability visualization showing where points escape to rather than where they escape from. It traces the trajectories of escaping points, creating a beautiful probability distribution. The technique was discovered by Melinda Green in 1993 11(#references).
Mathematical Insight: Instead of coloring by escape time, Buddhabrot accumulates density along escape trajectories. Points that take longer to escape contribute more to the final image, creating the characteristic "Buddha" silhouette. The mathematical properties of escape trajectories have been studied extensively 12(#references), revealing connections to probability theory and dynamical systems.
ShaderToy References:
- Buddhabrot by iq - Classic Buddhabrot implementation
- Buddhabrot Variations - Various Buddhabrot techniques
Signed Distance Functions and Ray Marching
Mathematical Foundation of SDFs
A Signed Distance Function d(p) returns the distance from point p to the nearest surface. The sign indicates inside (negative) or outside (positive). This mathematical representation enables rendering 3D shapes without explicit geometry.
Mathematical Foundation: SDFs are a form of implicit surface representation. Instead of storing vertices and triangles, we store a function that defines the surface as d(p) = 0. This connects to level sets in mathematics 15(#references).
Basic SDF primitives:
// Sphere: distance from point to center minus radius
float sdSphere(vec3 p, float r) {
return length(p) - r;
}
// Box: distance to axis-aligned box
float sdBox(vec3 p, vec3 b) {
vec3 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
}
Set Operations on SDFs
SDFs can be combined using set operations from constructive solid geometry (CSG) 30(#references):
- Union:
min(d1, d2)- mathematical union of two sets - Intersection:
max(d1, d2)- mathematical intersection - Subtraction:
max(d1, -d2)- set difference - Smooth Union:
mix(d1, d2, 0.5) - kwherekcontrols smoothness
Mathematical Insight: These operations work because SDFs satisfy the property that d(p) gives the exact distance to the boundary. The min and max operations preserve this property for unions and intersections 18(#references).
A comprehensive catalog of SDF primitives is maintained at 16(#references).
Ray Marching Algorithm
Ray marching finds where a ray intersects a surface defined by an SDF. The technique is based on sphere tracing, developed by John C. Hart 14(#references).
Mathematical Principle: If we know the distance d from point p to the nearest surface, we can safely step d units along the ray without overshooting the surface. This is guaranteed by the SDF property: the distance function gives the exact distance to the boundary.
The algorithm:
- Start at ray origin
ro - Calculate distance
d = SDF(ro + rd * t)whererdis ray direction - Step forward by
d:t += d - Repeat until
d < ε(hit) ort > maxDist(miss)
Mathematical Foundation: This is a form of fixed-point iteration applied to finding roots. We're solving SDF(ro + rd * t) = 0 for t, using the distance information to guide our search 14(#references).
Mathematical Concepts:
- Ray Parametrization:
p(t) = ro + rd * twheretis the parameter - Distance Fields: SDFs define surfaces implicitly as
d(p) = 0 - Normal Calculation: Using finite differences:
∇d ≈ (d(p+ε) - d(p-ε)) / 2ε - Set Operations: Combining SDFs using CSG operations
ShaderToy References:
- Ray Marching Tutorial by iq - Comprehensive ray marching guide
- SDF Collection by iq - Extensive library of SDF primitives
- Ray Marching Examples - Hundreds of ray marching demos
Procedural Noise and Natural Patterns
Fractal Brownian Motion
Procedural noise generates pseudo-random values that vary smoothly. The mathematical foundation is random fields - functions that assign random values to each point in space while maintaining spatial coherence.
Mathematical Types:
- Value Noise: Interpolated random values at grid points
- Gradient Noise (Perlin): Uses gradients instead of values, creating smoother patterns. Developed by Ken Perlin 31(#references)
- Simplex Noise: Faster alternative with better computational properties 32(#references)
- FBM (Fractal Brownian Motion): Multiple octaves of noise:
fbm(p) = Σ noise(p * 2ⁱ) / 2ⁱ
Mathematical Insight: FBM was introduced by Mandelbrot 19(#references) to model natural phenomena. The power-law scaling 1/2ⁱ creates self-similarity - the pattern looks similar at different scales, a key property of fractals.
Volumetric Rendering
Volumetric rendering uses noise to create realistic cloud patterns:
Mathematical Concepts:
- FBM for Density:
density = fbm(p * scale)creates multi-scale variation - Volume Integration: Accumulating density along rays:
∫ density(p(t)) dt - Light Transport: Solving the radiative transfer equation 23(#references) for participating media
- Tone Mapping: Converting HDR values using perceptual models 25(#references)
Modern implementations, as in Horizon Zero Dawn 26(#references), use sophisticated approximations of multiple scattering and anisotropic phase functions for real-time performance.
ShaderToy References:
- Volumetric Clouds by iq - Advanced cloud rendering
- Cloud Rendering Techniques - Various cloud implementations
Strange Attractors and Chaotic Systems
Strange attractors visualize the long-term behavior of chaotic dynamical systems. These mathematical objects reveal the structure of chaos through beautiful, intricate patterns.
Mathematical Insight: Strange attractors are sets of points in phase space that a dynamical system approaches over time. They have fractal structure and are sensitive to initial conditions - the hallmark of chaos. The Clifford attractor shown here is defined by the system:
x' = sin(a*y) - cos(b*x)
y' = sin(c*x) - cos(d*y)
Different parameter values create dramatically different patterns, revealing the rich structure of chaotic dynamics.
ShaderToy References:
- Strange Attractors by iq - Various attractor visualizations
- Clifford Attractor Collection - Different parameter sets
Three.js Integration
While our examples use pure GLSL, you can integrate these techniques with Three.js for more complex scenes. Here's how to use custom shaders in Three.js:
import * as THREE from 'three';
// Create a shader material with your GLSL code
const material = new THREE.ShaderMaterial({
uniforms: {
iTime: { value: 0 },
iResolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) },
iMouse: { value: new THREE.Vector2(0, 0) }
},
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform float iTime;
uniform vec2 iResolution;
uniform vec2 iMouse;
// Your fractal or mathematical shader code here
void main() {
vec2 uv = gl_FragCoord.xy / iResolution.xy;
// ... fractal calculation ...
gl_FragColor = vec4(color, 1.0);
}
`
});
// Apply to a plane or use as post-processing
const plane = new THREE.PlaneGeometry(2, 2);
const mesh = new THREE.Mesh(plane, material);
scene.add(mesh);
Three.js Resources:
- Three.js Shader Examples - Official examples
- Three.js Custom Shaders - Documentation
- Post-Processing with Three.js - Advanced techniques
Distance Estimation for Fractals
Smooth coloring in fractals uses distance estimation to avoid banding. The formula:
float smoothIter = float(iterations) + 1.0 - log2(log2(max(dot(z, z), 1.0)));
Mathematical Derivation: This comes from the relationship between iteration count and distance to the set boundary. For the Mandelbrot set, if zₙ is the value after n iterations, the distance to the boundary is approximately proportional to log(|zₙ|) / 2ⁿ. The double logarithm accounts for the exponential growth 4(#references), 28(#references].
This technique was developed by Linas Vepstas and others 4(#references), connecting iteration theory to visual representation. More sophisticated distance estimation techniques are described in 29(#references).
Learning Resources
ShaderToy Examples
ShaderToy is the premier platform for shader programming. Here are essential examples for mathematical and fractal shaders:
Fractals:
- Mandelbrot Set by iq - Classic with smooth coloring
- Julia Sets by FabriceNeyret2 - Interactive Julia exploration
- Newton Fractal by iq - Root finding visualization
Ray Marching:
- Ray Marching Tutorial by iq - Comprehensive guide
- SDF Collection by iq - Extensive primitive library
- 3D Scenes - Complex 3D scenes
Mathematical Visualizations:
- Strange Attractors - Chaotic systems
- Mathematical Art - Various mathematical patterns
Educational Resources
- Inigo Quilez's Articles: Deep dives into shader techniques and math - especially SDFs and ray marching
- The Book of Shaders: Step-by-step guide by Patricio Gonzalez Vivo
- Raymarching.com: Interactive tutorial on ray marching techniques
- Fractal Forums: Community discussions on fractal mathematics and rendering
- WebGL Fundamentals: Learn the underlying WebGL API
Try It Yourself
Experiment with these shaders in the GLSL Toybox - a full-featured shader editor where you can write, test, and modify shaders in real-time. All the examples above are available as presets you can explore and modify.
References
Academic Papers
-
Mandelbrot, B. B. (1980). "Fractal aspects of the iteration of z → z² + c for complex z and c." In Annals of the New York Academy of Sciences, 357(1), 249-259. DOI
-
Navarro, C. A., et al. (2020). "Efficient GPU Thread Mapping on 2D Fractals." arXiv preprint arXiv:2004.13475. arXiv
-
Douady, A., & Hubbard, J. H. (1984). "Étude dynamique des polynômes complexes." Publications Mathématiques d'Orsay, 84-02.
-
Vepstas, L. (1997). "Distance Estimation Method for Computing the Mandelbrot Set." Available at linas.org
-
Peitgen, H. O., & Richter, P. H. (1986). The Beauty of Fractals: Images of Complex Dynamical Systems. Springer-Verlag.
-
Shore, Z. (2019). "Rendering 3D Fractals." Master's thesis, Clemson University. PDF
-
Michelitsch, M., & Rössler, O. E. (1992). "The 'Burning Ship' and Its Quasi-Julia Sets." In Computers & Graphics, 16(4), 435-438.
-
Frame, M., et al. (2001). "Fractal Geometry." In Encyclopedia of Mathematics and its Applications, Cambridge University Press.
-
Hubbard, J. H., et al. (2001). "Newton's Method Applied to Two Cubic Equations." Complex Dynamics, 2nd ed., CRC Press.
-
McMullen, C. (1994). "The Mandelbrot Set is Universal." In The Mandelbrot Set, Theme and Variations, Cambridge University Press.
-
Green, M. (1993). "The Buddhabrot Technique." Available at superliminal.com
-
Ewing, J. H., & Schober, G. (1992). "The Area of the Mandelbrot Set." Numerische Mathematik, 61(1), 59-72.
-
Hart, J. C. (1996). "Sphere Tracing: A Geometric Method for the Antialiased Ray Tracing of Implicit Surfaces." The Visual Computer, 12(10), 527-545. DOI
-
Ricci, A. (1973). "A Constructive Geometry for Computer Graphics." The Computer Journal, 16(2), 157-160.
-
Quilez, I. "SDF Collection." Available at iquilezles.org
-
Quilez, I. (2007). "Smooth Minimum." Available at iquilezles.org
-
Mandelbrot, B. B. (1982). The Fractal Geometry of Nature. W.H. Freeman and Company.
-
Chandrasekhar, S. (1960). Radiative Transfer. Dover Publications.
-
Reinhard, E., et al. (2010). High Dynamic Range Imaging: Acquisition, Display, and Image-Based Lighting, 2nd ed. Morgan Kaufmann.
-
Schneider, A., et al. (2015). "Real-Time Volumetric Cloudscapes of Horizon Zero Dawn." ACM SIGGRAPH, 34(4). DOI
-
Douady, A., & Hubbard, J. H. (1985). "On the Dynamics of Polynomial-like Mappings." Annales Scientifiques de l'École Normale Supérieure, 18(2), 287-343.
-
Klebanoff, A. (2001). "Distance Estimation for the Mandelbrot Set." Fractals, 9(4), 397-407.
-
Requicha, A. A. G. (1980). "Representations for Rigid Solids: Theory, Methods, and Systems." ACM Computing Surveys, 12(4), 437-464.
-
Perlin, K. (1985). "An Image Synthesizer." ACM SIGGRAPH Computer Graphics, 19(3), 287-296. DOI
-
Perlin, K. (2001). "Noise Hardware." In Real-Time Shading, ACM SIGGRAPH Course Notes.
Online Resources
- ShaderToy: Online platform for shader programming, created by Inigo Quilez and others
- Inigo Quilez's Articles: Comprehensive collection of shader techniques and mathematical foundations
- The Book of Shaders: Step-by-step guide to shader programming by Patricio Gonzalez Vivo
- Raymarching.com: Interactive tutorial on ray marching techniques
- Fractal Forums: Community discussions on fractal mathematics and rendering
- WebGL Fundamentals: Learn the underlying WebGL API
- Three.js Shader Examples: Integration examples with 3D frameworks