Why it is necessary to set precision for the fragment shader?

Andrey Bushman picture Andrey Bushman · Feb 16, 2015 · Viewed 16.4k times · Source

I learn WebGL. Next shaders work fine:

// vertex.shader
// precision mediump float;
attribute vec4 a_Position;
attribute float a_PointSize;

void main(){
  gl_Position = a_Position;
  gl_PointSize = a_PointSize;
}

and

// fragment.shader
precision mediump float;
uniform vec4 u_FragColor;

void main(){
  gl_FragColor = u_FragColor;
}

Why it is necessary to set precission for the fragment shader? Vertex shader works without this, but fragment shader doesn't work without this code row (as I see). Why the different behaviour exist?

I read this before, but it didn't help me.

Answer

Andon M. Coleman picture Andon M. Coleman · Feb 16, 2015

No default precision exists for fp types in fragment shaders in OpenGL ES 2.0.

In vertex shaders, if you do not explicitly set the default precision for floating-point types, it defaults to highp. However, if the fragment shader were to default to highp as well, that would cause issues since OpenGL ES 2.0 does not require support for high precision floating-point types in the fragment shader stage.

OpenGL ES Shading Language - 4. Variables and Types - pp. 35-36

The fragment language has no default precision qualifier for floating point types. Hence for float, floating point vector and matrix variable declarations, either the declaration must include a precision qualifier or the default float precision must have been previously declared.

4.5.4 Available Precision Qualifiers

The built-in macro GL_FRAGMENT_PRECISION_HIGH is defined to one on systems supporting highp precision in the fragment language

#define GL_FRAGMENT_PRECISION_HIGH 1

and is not defined on systems not supporting highp precision in the fragment language. When defined, this macro is available in both the vertex and fragment languages. The highp qualifier is an optional feature in the fragment language and is not enabled by #extension.