Pro OpenGL ES for iOS

(singke) #1

316 CHAPTER 10: OpenGL ES 2, Shaders, and...^


„ Besides binding the attributes to named entities in the shaders, you
can also do the same with uniforms, as demonstrated in lines 6 and 7.
Remember that uniforms are merely values passed from the calling
program. (They differ from attributes in that attributes are mapped
one-to-one with each vertex.) In this case, we are supplying two
matrices and naming them modelViewProjectionMatrix and
normalMatrix. Looking again in the vertex shader, you can see the
following:
uniform mat4 modelViewProjectionMatrix;
uniform mat3 normalMatrix;
„ Lines 7ff support a memory optimization quark. Once linked, the
shader code is copied into the program, so the shader objects as we
have them are no longer needed. Since they use reference counts,
glDetachShader() serves to decrease the count by one, and, of
course, when 0, they can be safely deleted.
„ As a side effect, if you change the shader in anyway, it will have to be
relinked before the changes take effect. And in case you may have to
relink things, the driver may hold onto some cached information to use
later. Otherwise, the detach/delete process can aid the driver in
reusing the cached memory.
As you can see, the actual calls required are pretty minimal, but Apple’s demo includes
all of the error handling as well, which is why it was retained.
Now with that out of the way, we can look at the two shaders. Listing 10-5 is the vertex
shader, Shader.vsh. Note that the shaders pairs share the same prefix, with the vertex
shader having a suffix of vsh while the fragment shader uses fsh.
Listing 10-5. The Demo’s Vertex Shader

attribute vec4 position; //1
attribute vec3 normal;

varying lowp vec4 colorVarying; //2

uniform mat4 modelViewProjectionMatrix; //3
uniform mat3 normalMatrix;

void main()
{
vec3 normalDirection = normalize(normalMatrix * normal); //4
vec3 lightPosition = vec3(0.0, 0.0, 1.0); //5
vec4 diffuseColor = vec4(0.4, 0.4, 1.0, 1.0); //6

float nDotVP = max(0.0, dot(eyeNormal, normalize(lightPosition))); //7

colorVarying = diffuseColor * nDotVP; //8

gl_Position = modelViewProjectionMatrix * position; //9
}
Free download pdf