LearnMaking demos

Lesson 26 of 30 · 55 min

Fractals

Create endless detail with the Mandelbrot set, Julia sets and folding

In this lesson you will

  • Represent complex numbers as vec2 and write their multiplication and squaring
  • Draw the Mandelbrot set by counting steps until escape, and smooth that count for band-free color
  • Animate a zoom, and make a Julia set with a moving c
  • Build kaleidoscopic 2D patterns by repeating abs, rotation and scaling (folding)
  • Use folding in a 3D distance function and raymarch a self-similar solid

01Endless detail

This is the start of Part 4, "Making demos". Each lesson now takes one theme for building pieces (demos) that pull viewers in, combining the techniques you have learned. First up: fractals.

A fractal is a shape with endless detail: zoom into a part and you find something like the whole again. You see them in coastlines, branching trees and snowflakes. The surprise is that such complex shapes come from repeating a very short formula. Shaders are great at repeating the same math for every pixel, so fractals suit them perfectly.

In this lesson we start with a kind of number called a complex number and use it to draw the Mandelbrot and Julia sets. In the second half we use another approach, "folding" the coordinates, to make 2D patterns and a 3D solid.

02Complex numbers as vec2

A complex number pairs an ordinary number (the real part) with some multiple of i, a number whose square is -1 (the imaginary part). It is written a + b i. No need to overthink it: in a shader it is just a pair of numbers, so vec2(a, b) represents it directly. That means any point p on the screen can be read as a complex number.

Addition is just vec2 addition. For multiplication, expand and remember that i × i = -1: (a + b i)(c + d i) = (ac - bd) + (ad + bc) i. That is the function cmul. Squaring in particular is z × z = (x² - y²) + 2xy i, which you can write as vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y).

Squaring makes the most sense in terms of Polar coordinates. Squaring a complex number doubles its angle around the origin and squares its length. The picture below shows the angle as hue and the length as stripes. After squaring, the color wheel goes around twice.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Starts when it scrolls into view
Open in /edit ↗
▸Delete the z = cmul(z, z); line to compare with the original z. What does z = cmul(cmul(z, z), z); give?

Look at the stripes too. For the original z they are evenly spaced every 0.5 of length, but after squaring they crowd together toward the outside. A point at length 1.5 moves to 2.25 and one at 2.0 to 4.0: the bigger the number, the more it is stretched. This "beyond 1, squaring makes things grow fast" behavior is the key to the Mandelbrot set.

03The Mandelbrot set

The recipe for the Mandelbrot set is astonishingly short. For each pixel, take its position as a complex number c. Start with z at 0 and repeat z = z² + c over and over. If z grows and escapes, the point is outside the set. If it stays small forever, the point is inside.

Let's try some numbers. With c = 1, z goes 0 → 1 → 2 → 5 → 26 … and quickly blows up (outside). With c = -1, it goes 0 → -1 → 0 → -1 … back and forth and stays small forever (inside). With c = 0.5, it goes 0 → 0.5 → 0.75 → 1.06 → 1.63 → 3.15, passing 2 on the fifth step (outside).

We can't check "forever", so we make two agreements. First, once the length of z passes 2 it is known never to come back, so we call it escaped right there; to skip the square root we test dot(z, z) > 4.0. Second, if it hasn't escaped after 64 steps, we treat it as inside. Points outside are colored by how many steps it took to escape.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Starts when it scrolls into view
Open in /edit ↗
▸Change 1.2 (the visible range) to 0.6 and vec2(-0.6, 0.0) to vec2(-0.75, 0.15) to zoom in near the edge

The black region is the inside of the set. The colored bands outside are "points that escaped in 1 step", "in 2 steps", and so on, lined up by count. The closer a point is to the edge, the more steps it takes to escape. And the edge keeps revealing finer shapes no matter how far you zoom.

04Smooth coloring

The count is a whole number, so the colors come out in steps. Two neighboring points may both escape on step 10, but one may barely pass the line while the other leaps far past it. Using "how far it leaped", we can recover the fraction of a step.

After escaping, z roughly squares itself every step. The logarithm of its length doubles each step, so the log of that, log2(log2(|z|²)), grows by exactly 1 per step. Subtract it from the count n and the count becomes continuous. For example, a point whose |z|² was 70,000 on step 10 gives log2(log2(70000)) ≈ 4.01, so its smooth count is 10 - 4.01 + 4 ≈ 9.99. Another point that leaped to 4 billion on that same step gives ≈ 5.0 and a smooth count of 9.0: as if it had escaped a whole step earlier.

For this to be accurate, we widen the escape circle from radius 2 to radius 256 (dot(z, z) > 65536.0). The final + 4.0 lines things up so a point escaping exactly at radius 256 gets a fraction of 0 (because log2(log2(65536)) is 4).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Starts when it scrolls into view
Open in /edit ↗
▸Change sn * 0.04 to n * 0.04 and the bands come back. Change 0.04 to 0.15 and the colors cycle many times

05Zooming forever

Zooming is where fractals shine. Shrink scale in c = center + p * scale over time and you zoom toward the point center. A zoom looks natural when it keeps going "by the same ratio", so we shrink by repeated halving: pow(0.5, 11.0 * k). k swings 0 → 1 → 0 using cos, so the view dives in to 2048 times and comes back out.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

Starts when it scrolls into view
Open in /edit ↗
▸Change 11.0 to 15.0 to dive even deeper (when blocky squares appear, you have hit the precision limit)

Watch out

A shader float only has about 7 digits of precision. Zoom in around 100,000 times and neighboring pixels end up with the same c, so the picture breaks into square blocks. Videos of extremely deep zooms rely on special math tricks. For a demo, the easy route is to dive and return within the precision you have.

Tip

Pick a zoom target on the edge of the set, where color meets black. The inside (black) and the far outside show nothing new however far you zoom. The point used here, (-0.1011, 0.9563), sits on a branch growing out of the edge, where 64 iterations still show plenty of detail.

06Julia sets

In the Mandelbrot set, z starts at 0 and c is the pixel position. Swap those roles — start z at the pixel position and use the same c for every pixel — and you get a Julia set. The formula is the same z = z² + c.

Every value of c gives a completely different Julia set. Move c over time and the shape keeps morphing like a living thing. Here the iteration and the smooth count are wrapped in a function, iterate(z, c), which returns -1.0 when the point never escapes.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

Starts when it scrolls into view
Open in /edit ↗
▸Try 0.6 or 0.9 instead of 0.7885 and compare how the shape changes: sometimes it is one connected blob, sometimes scattered dust

The Mandelbrot and Julia sets are linked in a beautiful way: the Mandelbrot set is a map of Julia sets. If c is inside the Mandelbrot set, that c's Julia set is one connected shape; if it is outside, the Julia set is scattered dust. Choose c right near the edge for the most intricate and beautiful shapes. On the left below is the Mandelbrot set, with the white dot marking the current c; on the right is the Julia set for that c.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

Starts when it scrolls into view
Open in /edit ↗
▸Watch the right side connect when the white dot enters the black region, and break apart when it leaves. What happens if 0.7885 becomes 0.4?

Tip

Both halves call the same iterate; they differ only in what they pass as the starting z and as c. Each pixel computes only one side, so the cost is the same as a single picture.

07Folding

Now for another way to make fractals. In the kaleidoscope from Polar coordinates, we folded the angle to multiply a pattern. abs folds coordinates even more simply. q = abs(q) mirrors left-right and top-bottom, stacking the four quarters of the screen onto the top-right one. This is called folding.

1

2

3

4

5

6

7

8

9

10

11

Starts when it scrolls into view
Open in /edit ↗
▸Change q = abs(q); to q.x = abs(q.x); to mirror only left-right. Delete the line and you are back to one circle

We placed one circle in the top-right, and it became four. So what happens if we shift, rotate and scale the folded coordinates, then fold again? Each round multiplies the shape by four, each copy a little smaller and turned a little more. Five rounds give 4 to the 5th: 1,024 copies. This method is called KIFS (a Kaleidoscopic Iterated Function System).

  • Fold … abs(q) stacks the four quarters into one
  • Shift … move the stacked shape away from the center so the next fold multiplies it
  • Rotate … turn the fold lines so the result is not a plain grid
  • Scale … doubling the coordinates halves the shapes; divide distances by s at the end to get back to original units

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

Starts when it scrolls into view
Open in /edit ↗
▸Change the loop's 5 to 1, 2, 3 to watch it grow round by round. Change vec2(1.0, 0.6) or the rotation 0.4 for a completely different pattern

We divide the distance by s for the same reason as scaling in Moving space. A distance measured in space scaled up 2 times is half as long in the original space, so after five rounds (2 to the 5th = 32 times) we divide by 32. That way rings at every depth are drawn smoothly at a one-pixel width.

08Folding in 3D

Folding works in 3D just the same. Fold the coordinates inside the distance function map before placing a shape, and you can raymarch a solid made of many copies. As an example of folding across slanted planes, let's build the famous Sierpinski tetrahedron.

if (p.x + p.y < 0.0) p.xy = -p.yx; folds across the slanted plane x + y = 0: only points on the negative side of x + y are mirrored to the other side. For example, (x, y) = (-0.5, 0.2) has x + y = -0.3, so it is mirrored to (-0.2, 0.5), on the positive side. Folding across three such planes gathers points from any of the tetrahedron's four corners near the corner (1, 1, 1). Then p * 2.0 - vec3(1.0) scales by 2 around that corner.

Each round makes four copies, so after five rounds 1,024 spheres line up in the shape of a tetrahedron. Dividing by s at the end to restore the distance works just as in 2D. Since map contains a 5-round loop and is called inside a 64-step raymarch, this is fairly heavy. Use only as many rounds as you need.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

Starts when it scrolls into view
Open in /edit ↗
▸Change the loop's 5 to 3 or 6. Change the final sphere radius 1.4 to 1.0 to open up the gaps. What happens if you add p.xy = rot(0.2) * p.xy; inside the loop?

Watch out

Folding needs far fewer rounds than the loop limit of 64. At a scale factor of 2, six rounds already reach 1/64 of the size, smaller than a pixel on screen. More rounds won't change the picture; they only cost time.

09Exercises

Changing the formula just a little brings out a completely different fractal. Experiment freely.

Exercise 1

A cubic Mandelbrot

Draw the "cubic Mandelbrot set" by changing z = z² + c to z = z³ + c. The shape becomes symmetric around the origin, so also fix the position so it sits in the middle of the screen.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

Starts when it scrolls into view
Open in /edit ↗
Exercise 2

A Julia set you steer with the mouse

Right now c is fixed. When the cursor is over the canvas, set c from its position; when it isn't, move c around a circle. Then move the cursor around to hunt for beautiful shapes. The mouse only moves in the editor (/edit) and in lesson previews; on the work page and in the Gallery, mouse stays (0, 0). Make sure the piece still looks good with no cursor, so take care with the motion it has when the mouse is absent.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Starts when it scrolls into view
Open in /edit ↗
Exercise 3

A fractal tree

There is a single trunk. Repeat a fold so the tree splits into two branches again and again, getting thinner each time. Let the branch angle sway with time, as if in the wind.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Starts when it scrolls into view
Open in /edit ↗

10Recap

  • A complex number is a vec2. Squaring is vec2(x² - y², 2xy): the angle doubles and the length squares
  • The Mandelbrot set repeats z = z² + c from z = 0 and colors by the number of steps until |z| passes 2
  • Smoothing the count with n - log2(log2(dot(z, z))) + 4.0 removes the color bands
  • Zoom multiplicatively with pow; float precision lasts to about 100,000x
  • A Julia set swaps the roles of z and c; the Mandelbrot set is its map
  • Fold (abs or a mirror across a slanted plane) → shift → rotate → scale, repeated, makes self-similar shapes in 2D and 3D; divide the distance by the total scale at the end

Next up is "Tunnels and flight": tunnels that pull you into the screen and a camera that follows a winding path, for that unmistakable demo sense of speed.

Finished lessons get a mark in the course contents