Writing ESSL programs

Let's now take a step back and take a look at the big picture. ESSL allows us to implement a lighting strategy provided that we define a shading method and a light reflection model. In this section, we will take a sphere as the object that we want to illuminate and we will see how the selection of a lighting strategy changes the scene.

Writing ESSL programs

We will see two scenarios for Goraud interpolation: with Lambertian and with Phong reflections; and only one case for Phong interpolation: under Phong shading the Lambertian reflection model is no different from a Phong reflection model where the ambient and specular components are set to zero.

Goraud shading with Lambertian reflections

The Lambertian reflection model only considers the interaction of diffuse material and diffuse light properties. In short, we assign the final color as:

Final Vertex Color = Id

where the following value is seen:

Id = Light Diffuse Property * Material Diffuse Property * Lambert coefficient

Under Goraud shading, the Lambert coefficient is obtained by calculating the dot product of the vertex normal and the inverse of the light-direction vector. Both vectors are normalized previous to finding the dot product.

Now let's take a look at the vertex shader and the fragment shader of the example ch3_Sphere_Goraud_Lambert.html:

Goraud shading with Lambertian reflections

Vertex shader:

attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat4 uNMatrix;
uniform vec3 uLightDirection;
uniform vec4 uLightDiffuse;
uniform vec4 uMaterialDiffuse;
varying vec4 vFinalColor;
void main(void) {
vec3 N = normalize(vec3(uNMatrix * vec4(aVertexNormal, 1.0)));
vec3 L = normalize(uLightDirection);
float lambertTerm = dot(N,-L);
vec4 Id = uMaterialDiffuse * uLightDiffuse * lambertTerm;
vFinalColor = Id;
vFinalColor.a = 1.0;
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
}

Fragment shader:

#ifdef GL_ES
precision highp float;
#endif
varying vec4 vFinalColor;
void main(void) {
gl_FragColor = vFinalColor;
}

We can see that the final vertex color that we process in the vertex shader is carried into a varying variable to the fragment (pixel) shader. However, please remember that the value that arrives to the fragment shader is not the original value that we calculated in the vertex shader. The fragment shader interpolates the vFinalColor variable to generate a final color for the respective fragment. This interpolation takes into account the vertices that enclose the current fragment as we saw in Chapter 2, Rendering Geometry.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.64.47