$ cat tips/webgl-mediump-highp-mobile.md

WebGL shader noise is a grey smudge on a phone: precision mediump float

A phone's GPU computes mediump with less precision than the one in a computer, and the hash function that noise is made of then loses its fractional part. Ask for highp in the fragment shader wherever it is available.

#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

These lines go at the top of the fragment shader, in place of a bare precision mediump float;. In WebGL 1 highp in a fragment shader is optional, and the GL_FRAGMENT_PRECISION_HIGH macro is defined where the device supports it.

My shader draws smoke out of noise, and the noise comes from this function:

float hash(vec2 p) {
  p = fract(p * vec2(123.34, 456.21));
  p += dot(p, p + 45.32);
  return fract(p.x * p.y);
}

On the computer it was smoke. On a Pixel 9 Pro every grain came out the same and the smoke was a grey smudge.

The last line takes the fractional part of a product that runs into the thousands. The specification asks only 10 bits of precision of mediump, and with that many bits a number above 1024 has nothing left after the point.

gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision tells you how many bits mediump has on a given device.

You can connect to the phone without a cable, over Wi-Fi adb.

checked: Pixel 9 Pro, Chrome on Android

$ ls ./blog/tips
all tips →
↑