GLSL Learning

GLSL shader example

Random Numbers

GLSL has no random() function. Here is the one-line hash everyone uses, and how to turn it into random grid cells.

Live example

Edit the code and the preview updates as you type.

How it works

A shader runs the same code on every pixel at the same time, so there is no shared random number generator to call. Instead, shaders use a hash: a function that scrambles its input so much that the output looks random, while the same input always gives the same output.

random(st) does this in three steps:

  1. dot(st, vec2(12.9898, 78.233)) squashes the 2D input into one number.
  2. sin(...) * 43758.5453 turns it into a wave and multiplies it into a very large number, so tiny input changes produce huge output changes.
  3. fract(...) keeps only the decimal digits, which are the chaotic part, giving a value from 0% to 100%.

Feeding it floor(uv * 16.0) instead of raw uv gives every pixel in a cell the same input, so you get random blocks instead of TV static.

Try changing it

ChangeResult
random(cell + ...) to random(uv)Per-pixel static
16.0 to 4.0Big random blocks
floor(u_time * 2.0) to 0.0The pattern freezes
vec3(r) to vec3(step(0.5, r))Pure black and white cells, about half each

Note: this hash uses highp precision. On some mobile GPUs with mediump, the large multiplication loses precision and visible patterns appear.

Built-in functions used

Learn it step by step