10 11 12 13 14 15 16

Varying variables


In the previous lesson we've set three colors one for each of the vertices and got a smoothly colored triangle. How does it work?

Let's look again at the vertex shader:

#version 300 es
precision highp float;

in vec2 position;
in vec3 color;

out vec3 v_color;

void main(void)
    v_color = color;
    gl_Position = vec4(position, 0.0, 1.0);

gl_Position is a built-in output variable. However we can specify additional output variables. They're called Varying variables.

Varying variables are vertex shader output. Also they're fragment shader input. All you need to do is set vertex output varying values, and GPU will smoothly interpolate these values between pixels, and pass this interpolated data into fragment shader input data.

That could be considered as a generalization of a triangle rasterization process. You put a value into gl_Position for each of the vertices, and GPU interpolate these positions between vertices to get coordinates of each pixel. In the same way you can specify your own values you need to be interpolated between vertices. Let's look again at the fragment shader from the previous lesson:

#version 300 es
precision highp float;

// A vertex shader ouput parameter is an input parameter of a fragment shader
in vec3 v_color;

out vec4 frag_color;

void main(void)
    // Utilize v_color parameter to set the current pixel's color
    frag_color = vec4(v_color, 1.0);

The varying value should have the same type and name in vertex and fragment shaders. They're matched at the GLSL program linkage step. You put a value into a varying value inside a vertex shader, and whatever was put there, interpolated between vertices for each of the pixels.

There is a limit on how many varying variables you can use within a single GLSL program though. You can get this value with gl.getParameter(gl.MAX_VARYING_VECTORS) function:

const max_varyings = gl.getParameter(gl.MAX_VARYING_VECTORS);
console.log("Max GLSL varying variables: " + max_varyings);

Note that this function returns a maximum count of 4-components varying vectors. Which means that you can pack 4 times as much float values total.

You can get a full report on your WebGL capabilities with our WebGL report tool.

Lesson 14
Share this page:

Learning plan

Everything is ready to draw our first triangle
11. Uniforms
How to use draw call level parameters to control the shading process
Let's add more attributes to vertices and use them to enhance our triangle
13. Varying variables
How to evaluate a vertex-specified data and interpolate it between vertices
14. Textures
An introduction on how to load texture, initialize it properly with WebGL and pass it into GLSL program
15. glMatrix
How to install and use glMatrix library which provides vector and matrix arithmetics and helper functions
We've learned many thing by this point. Let's start organizing them neat and clean in the object-oriented way