Pro OpenGL ES for iOS

(singke) #1

CHAPTER 10: OpenGL ES 2, Shaders, and... (^317)
Here’s a closer look:
„ Lines 1f declare the attributes that we specified in the calling code.
Remember that attributes are arrays of data mapping directly to each
vertex and are available only in the vertex shader.
„ In line 2, a varying vector variable is declared. This will be used to pass
color information down to the fragment shader.
„ Lines 3f declare two uniforms that were originally specified in
loadShaders() earlier.
„ In Line 4, the normal is multiplied by the normalMatrix. You can’t use
the Modelview matrix in this case, because normals do not need to be
translated, and any scaling done in the Modelview would distort the
normal. As it turns out, you can use the inverse and transposed
Modelview matrix for the normals. With that in hand, the result is
normalized.
„ Lines 5 supplies the position of the light, while line 6 supplies the
default color. Normally you wouldn’t embed that data inside a shader,
but it is likely done this way just as a convenience.
„ Now, in line 7, the dot product of the normal (now called eyeNormal)
and the position of the light is taken to produce the angle between the
two. The max() function ensures that the return value is clamped to be



=0 to handle any negative values.
„ Now by simply multiplying the dot product by the diffuse color, as
shown in line 7, we get the luminosity of a face relative to the local
position of the light. The closer the normal aims toward the light, the
brighter it should be. As it aims away from the light, it will get darker,
finally going to 0.
„ gl_Position is a predefined varying in GLSL and is used to pass the
transformed vertex’s position back to the driver.
The fragment shader in this example is the most basic there is. It simply passes the
color info from the vertex shader through and untouched. gl_FragColor is another
predefined varying, and it is here where any final calculations would be made, as shown
in Listing 10-6.
Listing 10-6. The Simplest Fragment Shader
varying lowp vec4 colorVarying;
void main()
{
gl_FragColor = colorVarying;
}


Free download pdf