Fractals, step by step
glint · Examples · Tutorials · Gallery
Self-similarity, the Mandelbrot set (smooth colour, zooming, distance, orbit traps), Julia sets, the Burning Ship, Newton's fractal, Koch by folding, Apollonian circles by inversion, then 3D: Sierpinski, the Menger sponge, the Mandelbox, KIFS, quaternion Julia sets, the chaos game's fern, and an endless zoom.
A free interactive course of 20 steps in glint, a live shader editor in the browser: each step changes a running shader, and ticks itself when you've done its task.
1. The same at every scale
A fractal looks the same however far you zoom in: each part is a smaller copy of the whole. The simplest way to make one is a rule applied again and again, at smaller and smaller sizes.
The Sierpinski carpet's rule: cut the square into 3 × 3, throw away the middle one. Then do the same to each of the eight left, and to each of theirs. In the shader, each level scales the point up by 3 (p *= 3.0), checks if it's in the middle cell, and carries on inside its cell (fract).
With one level there's one hole. Every level makes the holes 3 times smaller and 8 times as many; after 5 there are 4,681. No loop over holes: each pixel just asks its way down.
Your turn: Go five levels down: const int ITER = 5;
2. The Mandelbrot set
Each pixel is a complex number c (x is its real part, y its imaginary part). Start z at 0, and repeat: z = z² + c. For some c, z stays small for ever; for others it grows and flies off. The Mandelbrot set is every c where it stays small. Outside it, the colour is how many rounds it took to escape.
Squaring a complex number (a + bi)² = a² − b² + 2abi, which in vec2 is vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y). Once |z| passes 2 it's certain to escape (dot(z, z) > 4.0).
Right now the loop only squares: 0 squared is 0, for ever, so every pixel stays and all is black. The + c is the whole fractal.
Your turn: Add c: z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;
3. Smooth colour
Colouring by the round it escaped on gives bands: every pixel that took 7 rounds gets the same colour. But z escapes by different amounts: one just over the line, another far beyond. That's the missing fraction.
Squaring makes |z| grow like a tower of powers, so the log of the log of |z| grows by about one each round. float(i) - log2(log2(dot(z, z))) cancels the jumps between rounds and leaves a smooth count. It needs z to have gone well past 2 for that to hold, so here it escapes at 256 (dot > 65536).
Your turn: Smooth it: float n = float(i) - log2(log2(dot(z, z))) + 4.0;
4. Zooming in, and where it ends
The Mandelbrot set's edge has detail at every scale: zoom in anywhere on it and there's more. The view is now c = centre + p * zoom, with the zoom shrinking exponentially (each second, about a third), starting over every 30 seconds.
Zooming into the middle of the black finds nothing: inside is all black. The interesting places are on the edge, like the valley between the main body and the round bulb on its left, full of seahorse tails.
Watch near the end of each zoom: the picture goes blocky. A GPU's float has about 7 digits, and by a zoom of 1/100,000 neighbouring pixels' c values are the same number. Deep-zoom programs use double precision or cleverer maths.
Your turn: Zoom into Seahorse Valley: vec2 centre = vec2(-0.7453, 0.1127);
5. Julia sets
Same rule, the other way round. In the Mandelbrot set each pixel is c and z starts at 0. In a Julia set, c is the same for the whole picture and each pixel is where z starts.
So every c gives a different Julia set: c inside the Mandelbrot set gives a connected shape, c outside it a scattered dust, and c right on its edge the most intricate ones. With c = 0, z just squares: everything inside the unit circle stays, so it's a disc.
Moving c round a circle of radius 0.7885 sweeps it along the edge of the Mandelbrot set, through spirals, dragons and lightning.
Your turn: Move c: vec2 c = 0.7885 * vec2(cos(time * 0.3), sin(time * 0.3));
6. Distance to the set
The Mandelbrot set's thinnest filaments are thinner than a pixel, so iteration colours mostly miss them. Like the distance functions of the raymarching courses, the set has a distance estimate: roughly how far c is from the set, worked out from z and how fast z changes as c moves (dz, its derivative, tracked alongside: 2·z·dz + 1).
0.5 * |z| * log|z| / |dz| is it. With a distance, drawing a line of even width is easy: dark within a couple of pixels of the set, light beyond. Every filament shows, however thin, like a pen drawing.
The same estimate is how 3D fractals are raymarched: later steps use it.
Your turn: Estimate the distance: float d = 0.5 * sqrt(dot(z, z) / dot(dz, dz)) * log(dot(z, z)) * 0.5;
7. Orbit traps
The values z takes on the way are its orbit. An orbit trap watches how close the orbit comes to some shape: here a small circle. Points whose orbits pass right by it get a value near 0, and since neighbouring points have similar orbits, the closeness changes smoothly and draws copies of the trap's shape all through the fractal, distorted by it.
trap is already worked out. Colouring by it turns this Julia set into rings of loops and flowers. Try other traps after: a point (length(z - vec2(0.5))), a line (abs(z.y)), a cross (min(abs(z.x), abs(z.y))).
Your turn: Colour by the trap: col += palette(trap * 3.0) * exp(-trap * 8.0);
8. The Burning Ship
Small changes to the rule give whole new fractals. Take the absolute value of z's parts before squaring and the Mandelbrot set becomes the Burning Ship: its main part looks like a ship on fire, with masts and flames of smaller ships.
In the squaring, that only changes the imaginary part: 2.0 * abs(z.x * z.y). The view is turned upside down and moved to the ship (it sits on the negative real axis).
Your turn: Burn it: z = vec2(z.x * z.x - z.y * z.y, 2.0 * abs(z.x * z.y)) + c;
9. Newton's fractal
Newton's method finds where a function is zero: guess, then jump to where the function's slope line crosses zero, z - f(z) / f'(z), and repeat. Usually it settles on an answer in a few jumps.
z² − 1 has two answers (±1), and the plane splits cleanly in two: left goes to −1, right to +1. Not a fractal. But z³ − 1 has three (the cube roots of 1), and the borders between where guesses end up are fractal: wherever two colours meet, the third is there too, at every scale.
For z³ − 1 the slope is 3z². cmul and cdiv multiply and divide complex numbers.
Your turn: Use z³ − 1: z -= cdiv(cmul(cmul(z, z), z) - vec2(1.0, 0.0), 3.0 * cmul(z, z));
10. Folding a snowflake
The Koch snowflake: take a triangle, add a spike to the middle third of each edge, then to each new edge, for ever. Its outline is infinitely long around a finite area.
Drawing it by adding spikes would mean millions of lines. Folding goes the other way: mirror the plane so every point lands on one edge, then at each level scale up by 3 and fold the middle third along a line at ANGLE, which is what makes the spike. After five levels, measure the distance to a straight line and divide by the total scale.
The fold's angle is the spike's shape: 2/3 of π gives Koch's 60° spikes. Others give other curves.
Your turn: Change the spikes: const float ANGLE = 0.6 * PI;
11. Circles inside circles: inversion
Circle inversion turns the plane inside out round a circle: a point at distance r goes to distance 1/r, so the inside swaps with the outside, and circles stay circles. Fold space into a repeating cell, invert, fold, invert…: the Apollonian gasket, circles packed between circles at every size.
S scales the inversion: how far inside out each round turns the cell. Small changes repack every circle at every size at once, because every level is made by the same rule. Try values between 1.0 and 1.4 after.
Your turn: Repack it: const float S = 1.15;
12. 3D: the Sierpinski tetrahedron
Into 3D, with the same idea as the carpet but by folding. if (p.x + p.y < 0.0) p.xy = -p.yx; mirrors space across a plane, so points on one side are measured as if on the other. Three such planes fold all of space into one corner of a tetrahedron; scaling by 2 and moving that corner to the middle makes four half-size copies. Nine rounds: 262,144 little balls.
Distances got scaled by 2 each round too, so dividing by s at the end gives a real distance, safe to march (the Advanced course's fractal step explains why).
With only two of the three folds, it's a lopsided half of the shape.
Your turn: Add the third fold: after the second if, add if (p.y + p.z < 0.0) p.zy = -p.yz;
13. The Menger sponge
The carpet in 3D: a cube with a cross-shaped tunnel through the middle of every face, then through every smaller cube left, and so on.
Each round, mod repeats space into little cubes at that level, c is the distance to the cross of three tunnels through each one, and max(d, c) carves them out (a max is an intersection: keep what's in the cube and not in a tunnel). Four rounds: 160,000 cubes' worth of holes, for the cost of four crosses.
Right now the crosses are worked out but never carved.
Your turn: Carve: after the float c line, add d = max(d, c);
14. The Mandelbox
Tom Lowe's Mandelbox: fold space into a box (past ±1, mirror back in), fold it into a ball, scale, and add the starting point, like the Mandelbrot set's + c. The box fold makes the straight walls and corners; the sphere fold turns small things inside out and brings in curves, rings and towers.
In the sphere fold, points very near the middle get scaled up a lot (×4), points inside the unit ball get inverted (p /= r2), and points outside are left alone. dr tracks the total scaling, so the distance can be divided by it.
Without the sphere fold it's a lumpy box.
Your turn: Add the sphere fold: after float r2 = dot(p, p); add if (r2 < 0.25) { p *= 4.0; dr *= 4.0; } else if (r2 < 1.0) { p /= r2; dr /= r2; }
15. Colour from the orbit
A 3D fractal can be coloured the way the 2D ones were: by its orbit. trap keeps the smallest r2 the point reached during the folds, a number that changes smoothly over the surface and differently on each kind of part, so walls, rings and towers each get their own colours.
Fed through a cosine palette (the sqrt spreads it more evenly), the stone Mandelbox becomes a painted one.
Your turn: Colour it: vec3 albedo = 0.5 + 0.5 * cos(6.2832 * (sqrt(trap) * 0.6 + vec3(0.0, 0.15, 0.3)));
16. Kaleidoscopic folds
KIFS (kaleidoscopic iterated function systems): fold into one corner with abs, sort the axes (three more mirrors: now a 48th of space), turn, scale, shift, repeat. Each round copies everything 48 times.
The turn is what brings it to life: with no turn every copy is square to the last and it's a blocky cluster. Turned, the copies twist into crystals, spires and machinery, and animating the angle makes it grow and fold in on itself.
Your turn: Turn it, slowly changing: float angle = 0.3 + 0.25 * sin(time * 0.2);
17. A Julia set in 3D
Complex numbers have one imaginary part; quaternions have three, so z² + c works in 4D. Raymarching a 3D slice of it (the fourth number 0) gives a quaternion Julia set: smooth, blobby, like poured metal.
As in 2D, every C gives a different shape. C is a quaternion (vec4). Sweeping its four parts slowly, each at its own speed, makes the shape melt and reform continuously.
The distance estimate is the 2D one again: |z| log|z| / |dz|.
Your turn: Animate it: C = 0.45 * cos(vec4(0.5, 3.9, 1.4, 1.1) + time * vec4(0.6, 0.85, 0.65, 1.25)) - vec4(0.3, 0.0, 0.0, 0.0);
18. The chaos game: a fern from points
A completely different way to make a fractal: play a game of chance. Start a point at 0 and take random steps, each one of four simple maps (a little matrix and a shift: shrink, turn, move). Wherever the point ends up after 40 steps, draw a dot. 400,000 points later, Barnsley's fern appears.
This is a vertex shader (the Vertex shaders course): 400,000 points, Vertices only, Draw mode Points, each running its own game from its own random numbers. Additive blending piles the dots up into light.
Each map draws one part: the 85% one makes the next smaller frond up the stem, turned by lean. Change it and the whole fern curls, at every scale, because every frond is a copy of the whole.
Your turn: In the Vertex tab, curl it: float lean = 0.08;
19. An endless zoom
The carpet again, zooming into its bottom-left corner. It zooms by pow(3.0, -time * 0.3): a third smaller each few seconds, for ever, until (as with the Mandelbrot zoom) the numbers run out of digits and it falls apart, in about a minute.
But the carpet is exactly self-similar: its bottom-left ninth is the whole carpet, a third the size. So after zooming by 3, the picture is the same as at the start. Zoom from 1 to 3 and jump back, using fract(time * 0.3), and the jump can't be seen: an endless zoom that never runs out.
Any exactly self-similar fractal can loop like this, at its own scale factor.
Your turn: Loop it: float zoom = pow(3.0, -fract(time * 0.3));
20. Pull it apart: a Mandelbox full of holes
A Mandelbox, coloured by its orbit. But it's broken: there's almost nothing there, a few specks at most, as if the rays went straight through it.
They do. The distance de returns is wrong: far too big, so every step of the march jumps past the surfaces.
Hint: every round of folds scales space up by SCALE (and the sphere fold by more). The distance at the end is measured in that scaled-up space. What tracks how much it was scaled?
Your turn: Fix the distance.
Other courses: Basics · Medium · Advanced · Maths for shaders · Raymarching, step by step · Matrices, from scratch · Sound you can see · Noise from scratch · Colour and light · Passes and feedback · Skies and reflections · Vertex shaders, step by step · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Raymarching 4: modelling, materials and motion · Vertex shaders 2: lines, particles and moving meshes · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow