OpenGL varying variables explained

Couple of months ago I posted a article about circle rendering using OpengES 2.

I have to admit, back then I did not understand varying variables fully.

Now I have much better understanding.

OK, let’s analyze simple vertex shader

uniform mat4 mvp_matrix;
uniform vec4 u_color;
attribute vec4 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main()
gl_Position = mvp_matrix * a_position;
v_texcoord = a_texcoord;

First, we have two uniform variables. Uniforms are set during runtime by main application.

Second, two variables marked as attribute.

Values of attribute variables are fetched from buffer. Buffer have to be filled with vertex/texture coordinates, plus OpenGL have to be informed about buffer data format.

Finally a single variable marked varying.

Couple of lines later varying variable have assigned value – it’s a copy of value stored inside a_texcoords attribute.

Now, lets look at fragment shader.

uniform sampler2D texture;

varying vec2 v_texcoord;

void main()
  gl_FragColor = texture2D(texture, v_texcoord);

gl_FragColor is a build-in OpenGL variable. Fragment color is determinated by value assigned to that variable.

texture2s(texture, v_textcoords) function calculates color value using current texture and texture coordinates.

But how texture coordinates are calculated? Only data we have, are UV-s stored inside buffer with vertex coordinates.

First, remember how shaders work. To render a triangle:

  • Vertex shader is executed for each vertex
  • Fragment shader is executed for each pixel

So, varying variable have value assigned three times (one time for each vertex shader)

Now, OpenGL calculates varying variable value for each fragment shader. Obviously varying variable value have to be different for each fragment shader call.

Calculation takes values of varying variable generated by vertex shader, and relative position of fragment.

Exact formula is not important. Can by googled. The point is – value of fragment shader varying variable is calculated – calculation formula is using fragment (relative) position, and varying values calculated by vertex shader.


Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:


Komentujesz korzystając z konta Wyloguj /  Zmień )

Zdjęcie na Google

Komentujesz korzystając z konta Google. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

Połączenie z %s

%d blogerów lubi to: