LearnPatterns and noise

Lesson 11 of 30 · 50 min

Making randomness

Build pseudo-random numbers with hash functions for per-cell variety and Truchet tiles

In this lesson you will

  • Know why GLSL has no random(), and how a hash function turns a position into a random-looking number
  • Understand the classic fract(sin(…) * 43758.5453) trick and its pitfalls, and use hash21 instead
  • Use cell numbers to vary color, size, angle and presence from cell to cell
  • Draw Truchet tiles, the maze-like pattern
  • Make random values that change over time with floor(time), and get two at once with hash22

01There is no random() in GLSL

A little variation brings a picture to life: the positions of stars in a night sky, the colors of mosaic tiles, the angles of falling confetti. Their natural feel comes from not being perfectly regular. In Repetition and tiles you varied each cell by feeding its number into sin. But sin is a wave, so if you look closely you can see the regular repeat. What we really want are numbers that look truly haphazard: random numbers. In most programming languages you would call something like random() to get one, but GLSL has no such function.

The reason is how shaders run. As you saw in Your first shader, the same function runs for every pixel at the same time. An ordinary random generator remembers the last number it produced and derives the next one from it. Millions of pixels running in parallel can't take turns updating one shared memory. And if every frame produced fresh random numbers, the picture would flicker 60 times a second.

So we flip the idea around. What we want is a function that takes a position and returns a number that looks random. Give it the same position and you always get the same number, so the picture holds still. Give it a slightly different position and you get a number that seems completely unrelated. Such a function is called a hash function, and its output is a pseudo-random number: the result of a fixed calculation that merely looks random.

Tip

Always getting the same answer for the same input is a strength, not a weakness. The same starry sky appears every time the work is opened, and its still thumbnail comes out the same every time too.

02The classic hash

One line has been used in shaders for a very long time: fract(sin(x) * 43758.5453). It works in three steps. sin(x) is a wave that glides smoothly between -1 and 1. Multiplying by a big number like 43758.5453 stretches tiny differences in x into large ones. Finally, fract keeps only the part after the decimal point: the whole-number part is thrown away and only the fine digits remain. Those fine digits are what look random.

Let's check with numbers. When x is 1.0, sin(x) is 0.841471. Times 43758.5453 that is 36821.546, and its fract is 0.546. Change x to 1.01 and sin(x) barely moves, to 0.846832. But after the multiplication it becomes 37056.13, and the fract is 0.13. The inputs differ by only 0.01, yet the answers look completely unrelated.

The preview below takes 60 values of x, each 0.1 apart, and draws fract(sin(x) * k) as the height of a bar. k is the stretch factor.

1

2

3

4

5

6

7

8

9

Starts when it scrolls into view
Open in /edit ↗
▸Raise k to 10.0, then 100.0, then 43758.5453. The wave falls apart step by step until the heights look random

With k at 1.0 you can still see the sin wave. (The jump halfway across happens because fract of a negative number counts down from 1.0: fract(-0.3) is 0.7.) As k grows, the wave gets folded over again and again, and each bar stops having anything to do with its neighbors. The bigger the multiplier, the more random it looks.

To use it on a 2D point, first fold the two numbers into one, then pass that to sin. dot(p, vec2(12.9898, 78.233)) is the same as p.x * 12.9898 + p.y * 78.233: it adds x and y with odd-looking weights. With round weights, different points would land on the same sum too often, so the weights are deliberately messy.

1

2

3

4

5

6

7

8

Starts when it scrolls into view
Open in /edit ↗
▸Every pixel gets its own value, like static on an old TV. Change classic(uv) to classic(uv + fract(time)) and the static starts to crawl

03Where the classic hash falls short

Because this one-liner is short and easy to remember, it spread through books and examples everywhere. But it has a few pitfalls. The first thing to understand is that a hash function isn't magic. It's just an ordinary function that changes extremely fast. Feed it the wrong numbers and its hidden regularity shows up as a visible pattern.

1

2

3

4

5

6

7

8

9

10

11

Starts when it scrolls into view
Open in /edit ↗
▸Set scale to 0.00001. Then put scale back to 1.0 and set offset to 100000.0. Either way, stripes or diagonal patterns show through the static
  • Inputs too close together: if neighboring points differ by only a tiny amount, the sin wave isn't stretched enough, and what's left of the wave shows up as stripes
  • Inputs too large: a float holds only about 7 significant digits. Feed it a big number and the fine digits that should create the randomness get rounded away, leaving a regular pattern
  • Different GPUs, different answers: the GLSL spec leaves the precision of sin up to the GPU. The sin of a large number varies the most, so you can get clean static on your laptop and stripes on some phones

The first two apply to every hash function. The third is specific to this classic one-liner. Your work runs on the viewer's GPU, so looking fine on your screen does not guarantee it looks the same on theirs.

04This course's hash: hash21

So in this course we use a hash function called hash21, which avoids sin and uses only multiplication, addition and fract. Those operations give practically the same answer on every GPU, so the picture depends far less on the viewer's hardware. The 21 in the name means "2 numbers in (vec2), 1 number out (float)".

1

2

3

4

5

float hash21(vec2 p) {

p = fract(p * vec2(123.34, 456.21));

p += dot(p, p + 45.32);

return fract(p.x * p.y);

}

  • p = fract(p * vec2(123.34, 456.21)) multiplies x and y by large, messy numbers and keeps only the fractional parts. Everything is now between 0 and 1, so the numbers never grow too large in the steps that follow
  • p += dot(p, p + 45.32) builds one number from both x and y and adds it to each, so x now depends on y and y depends on x
  • fract(p.x * p.y) multiplies the two into one number and returns its fractional part, which is at least 0 and less than 1

1

2

3

4

5

6

7

8

9

10

Starts when it scrolls into view
Open in /edit ↗
▸Change hash21(uv) to hash21(uv + fract(time)) to animate the static. The fract keeps the input small even as time keeps growing

Watch out

hash21 also shows patterns when its input is too large — the digit limit of a float is the same for every hash function. It's safest to keep inputs within a few hundred, like cell numbers. Even for pixel-fine static, small coordinates such as uv are all you need.

05One random number per cell

Random values per pixel only ever give you static. What's far more useful for pictures is one random number per cell. In Repetition and tiles you saw that floor(p * n) gives the number of the cell a point falls in. Every point in a cell shares that number, so passing it to hash21 gives one value across the whole cell and a different one in the next.

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 ↗
▸Set n to 12.0 for smaller cells. Change hash21(id) to hash21(id + 0.5) and the whole color arrangement changes

mask is the same kind of mask you made in Circles and distance: 1 inside the shape and 0 outside. The edge-smoothing width px needs care, though. Since we multiplied p by n to make the cells, one pixel is n times larger in the cell coordinates gv. That's why 2.0 / resolution.y is multiplied by n as well.

Add a fraction before hashing, as in hash21(id + 0.5), and you get a completely different set of random numbers. The number you add is called a seed. When you need several random numbers for one cell, call the hash several times with different seeds: hash21(id), hash21(id + 0.31), hash21(id + 0.73).

Watch out

Avoid adding whole numbers as seeds. hash21(id + 1.0) is exactly the value of the diagonal neighbor id + vec2(1.0, 1.0). If you use one for color and the other for size, every cell's size matches its diagonal neighbor's color, and a diagonal pattern gives the trick away.

06Size, angle, and whether it's there

With the in-cell position gv, you can draw a different shape in each cell. Use a random number as the radius and the sizes vary; compare one against a threshold and you decide whether to draw at all. A random number between 0 and 1 is below 0.3 in roughly 30% of the cells.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change 0.3 to 0.7 and more cells go empty. Change the two numbers in mix(0.12, 0.45, size) to widen or narrow the range of sizes

Angles work the same way. Multiply a random number between 0 and 1 by TAU (one full turn, about 6.28) and you get an angle anywhere from 0 to 360 degrees. To turn the shape by that angle, do as in Moving space: rotate the in-cell coordinates the opposite way with rot(-angle), then draw the shape.

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

Starts when it scrolls into view
Open in /edit ↗
▸Replace hash21(id) * TAU with floor(hash21(id) * 4.0) * PI * 0.5 and only four directions remain. Then add + time * (hash21(id + 0.73) - 0.5) * 4.0 to the end of the angle line and each stick spins at its own speed

Watch out

Keep each shape small enough to stay inside its cell at any angle. The shader only ever looks at the cell the current point is in. Anything that pokes out would have to be drawn by the neighboring cell, which knows nothing about it, so the shape gets sliced off at the cell border. The sticks above are short enough that even their corners stay within 0.5 of the center.

07Truchet tiles

Just picking one of two tiles at random in each cell produces surprisingly intricate patterns. These are called Truchet tiles, after Sébastien Truchet, a French scholar who studied tile arrangements in the early 1700s. In the 1980s a one-line BASIC program, 10 PRINT, became famous for drawing a maze simply by printing / or \ at random, over and over.

Let's start with the same maze as 10 PRINT. In each cell, draw a diagonal segment from the bottom-left corner to the top-right corner (that's sdSegment from Combining shapes). In cells whose random number is below 0.5, flip the sign of gv.x. That mirrors the cell left to right, so the line runs from bottom-right to top-left instead.

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 0.5 to 0.2 or 0.9. One direction takes over, and the maze turns into a pattern with a flow to it

Every line runs corner to corner, so it meets the lines in neighboring cells exactly at the corners. That's why, although each tile is just a diagonal stroke, together they read as a maze full of dead ends and forks.

Next, replace the diagonal with two quarter-circle arcs. Draw circles of radius 0.5 around the bottom-left and top-right corners, and both arcs pass exactly through the midpoints of the cell's edges. The neighboring cells' arcs pass through those midpoints too, so flipped or not, the curves always join smoothly. The distance to an arc is the same abs(length(…) - r) you used for rings in Circles and distance.

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

Starts when it scrolls into view
Open in /edit ↗
▸Set w to 0.25 and the bands thicken into something like knitting. Change 0.5 to 0.1 to skew the mix of directions

08Random numbers that change over time

time grows smoothly, but floor(time) is a whole number that goes up by one each second. Mix it into the hash input and you get a fresh random number every second. floor(time * 4.0) changes four times a second; floor(time * 0.5) once every two seconds.

There's one catch in how you mix it in. If you write hash21(id + floor(time)), then one second later cell id takes on the value its diagonal neighbor id + vec2(1.0, 1.0) has right now — the same reason whole-number seeds are a bad idea. Instead of rerolling, the pattern just slides diagonally. Multiply floor(time) by an odd fraction like 0.37 before adding it, and every step gives genuinely new values.

The example below also gives each cell its own clock. Adding hash21(id + 0.5) to time makes every cell switch at a different moment, so instead of the whole grid changing at once, cells flip here and there. fract(t) is 0 right after a switch and climbs toward 1 before the next, so multiplying the brightness by 1.0 - fract(t) makes each cell flash when it changes and then settle down.

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

Starts when it scrolls into view
Open in /edit ↗
▸Change 0.37 * beat to just beat and the colors stop being new: the pattern simply drifts diagonally. Remove + hash21(id + 0.5) and every cell switches at the same moment

Tip

Here the colors snap from one to the next. If you blend the previous and next random numbers with mix(previous, next, fract(t)), the value glides from one to the other instead. Stretching that idea further gives you noise, the topic of the next lesson.

09Two random numbers at once: hash22

To decide where in a cell to put a point, you need two random numbers, one for x and one for y. You could call hash21 twice with different seeds, but hash22 hands you both at once as a vec2. As the name says, it takes 2 numbers and returns 2; inside, it's the same idea as hash21, stretched to three numbers.

1

2

3

4

5

vec2 hash22(vec2 p) {

vec3 a = fract(p.xyx * vec3(123.34, 234.34, 345.65));

a += dot(a, a + 34.45);

return fract(vec2(a.x * a.y, a.y * a.z));

}

Let's use it to build a starry sky. Divide the screen into cells and place one star in each, at a position chosen by hash22. hash22 returns values from 0 to 1, so - 0.5 shifts them to -0.5 to 0.5, and multiplying by 0.8 narrows that to -0.4 to 0.4, so no star spills over its cell edge and gets clipped. Brightness, twinkle speed and twinkle timing also vary per star, using hashes with different seeds.

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

Starts when it scrolls into view
Open in /edit ↗
▸Set pos to vec2(0.0) and the stars line up in a rigid grid. You can see how much the scattered positions add to the natural look. Set n to 20.0 for more stars

Tip

The idea of one point per cell, nudged by hash22, takes center stage in Cellular patterns (Voronoi). Measure the distances between those points and you get patterns like cells and cracks.

10Exercises

Feed cell numbers to hash21, change seeds to get more random numbers, and use floor(time) to make them change over time. Put those three moves to work in your own code.

Exercise 1

Windows at night

A building wall is covered in windows, and right now every one of them is lit. Use random numbers so that only about 30% of the windows are lit. Vary the brightness of the lit ones a little, and mix in a few windows with a bluish fluorescent white.

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 ↗
Exercise 2

Truchet's triangle tiles

The tiles Truchet first studied were squares split diagonally into two colors. In the starter every tile faces the same way, so all you see are big diagonal stripes. Rotate each tile at random by 0, 90, 180 or 270 degrees to make a Truchet pattern.

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 ↗
Exercise 3

Equalizer

Make a row of dancing bars like the equalizer on a music player. In the starter, all 24 bars have the same height. Give each bar a random height that changes four times a second. Then, if you can, split the bars into stacked LED-like blocks and color them green at the bottom, turning yellow and then red toward the top.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Starts when it scrolls into view
Open in /edit ↗

11Recap

  • GLSL has no random(). Instead, a hash function turns a position into a fixed number that looks random
  • The classic fract(sin(…) * 43758.5453) is short, but sin precision varies between GPUs. This course uses hash21
  • Feed hash functions numbers that are neither too close together nor too large; cell numbers, a few hundred at most and one apart, are ideal
  • Hashing the cell number from floor gives one random number per cell. For more of them, add fractional seeds
  • Mixing in floor(time) times an odd fraction gives random numbers that change over time. hash22 returns two at once

Next time we join these scattered random values smoothly to build noise, the raw material for clouds and landscapes.

Finished lessons get a mark in the course contents