Home opengl - q&a
Post
Cancel

opengl - q&a

In WebGL what are the differences between an attribute, a uniform, and a varying variable?

In OpenGL, a “program” is a collection of “shaders” (smaller programs), which are connected to each other in a pipeline.

Shaders process vertices (vertex shader), geometries (geometry shader), tessellation (tessellation shader), fragments (pixel shader), and other batch process tasks (compute shader) needed to rasterize a 3D model.

OpenGL (WebGL) shaders are written in GLSL (a text-based shader language compiled on the GPU).

Keeping these concepts in mind:

Shaders can pass data to the next shader in the pipeline (out, inout), and they can also accept data from the WebGL application or a previous shader (in).

  • The Vertex and Fragment shaders (any shader really) can use a uniform variable, to receive data from the WebGL application.

    1
    2
    3
    
    // Pass data from WebGL application to shader
    const uniformHandle = gl.glGetUniformLocation(program, "vertexVariableA");
    gl.glUniformMatrix4fv(uniformHandle, 1, false, [0.1, 0.2, 0.3], 0);
    
  • The Vertex Shader can also receive data from the WebGL application with the attribute variable, which can be enabled or disabled as needed.

    1
    2
    3
    4
    
    // Pass data from WebGL application to Vertex Shader
    const attributeHandle = gl.glGetAttribLocation(mProgram, "vertexVariableB");
    gl.glEnableVertexAttribArray(attributeHandle);
    gl.glVertexAttribPointer(attributeHandle, 3, gl.FLOAT, false, 0, 0);
    

    another answer

  • The Vertex Shader can pass data to the Fragment Shader using the varying variable. See GLSL code above (varying vec3 variableC;).

  • uniform are per-primitive parameters (constant during an entire draw call) ;

  • attribute are per-vertex parameters (typically : positions, normals, colors, UVs, …) ;

  • varying are per-fragment (or per-pixel) parameters : they vary from pixels to pixels.

This post is licensed under CC BY 4.0 by the author.