Shading

To render geometry interactively, we require a shader that performs transformation.

To render colorful geometry, we require it to receive vertex color data via a vertexColor attribute. This attribute is initialized and rendered exactly like the vertexPosition attribute that it accompanies.

〈Vertex Shader〉 ≡
  precision mediump float

  uniform mat4 projectionMatrix
  uniform mat4 viewMatrix
  uniform mat4 modelMatrix

  attribute vec4 vertexPosition
  attribute vec3 vertexColor

  varying vec3 fragmentColor

Here is the pseudocode of a vertex shader that copies the vertex color to the fragment and transforms the vertex position using matrix multiplication.

  function main()
    fragmentColorvertexColor
    gl_PositionprojectionMatrix * viewMatrix * modelMatrix * vertexPosition

Here is the pseudocode of a fragment shader compatible with this vertex shader. It receives the color value given to it by the vertex shader and writes it to the frame buffer with an opaque alpha value.

〈Fragment Shader〉 ≡
  precision mediump float
  varying vec3 fragmentColor
  function main()
    gl_FragColorvec4(fragmentColor, 1.0);

On the application side, we set up for rendering with this shader as follows.

We'll need to know the locations of the shader uniforms to give them values, Since we'll want to be able to set uniform values from anywhere in the code, such as in the draw function, their locations should be stored globally.

〈Initialize the uniform objects〉 ≡
  projectionMatrixLocation ← gl.getUniformLocation(program, “projectionMatrix”);
  viewMatrixLocation ← gl.getUniformLocation(program, “viewMatrix”);
  modelMatrixLocation ← gl.getUniformLocation(program, “modelMatrix”);