5.2 Blinn-Phong Fragment Shader

Now we are going to implement the Blinn-Phong Fragment Shader

Create blinn.frag

Create blinn.frag in folder shaders.

Declare Input variables from the vertex shader

First we are going to delare the variables from the vertex shader. They are the fragment position in the world space (fragPos) and the normal vector in the world space (normal).

#version 410

// for lighting
in vec3 fragPos;
in vec3 normal;

Declare Uniforms

The uniforms required for light computing are the light source position (lightPos) and the camera position (viewPos).

uniform vec3 lightPos;
uniform vec3 viewPos;

Declare output variables

The only ouput is the colour of the fragment (pixel)

The main() function

Note: In this lab we are using hardcoded surface colour, light source colour, ambient, diffuse and specular coefficients.

This is not a good practice and should be replaced by material parameters and textures in the future.

Set the surface colour

Here we are hardcoding the diffuse surface colour. In the future, it is going to be replace by the colour from the texture.

The ambient component

here, the ambient component is simply based on the surface colour.

The diffuse component

The diffuse component is calculated based on the cosine of the angle between the light direction and the surface normal. It is independant from the view direction.

The specular component

In Blinn-Phong model, we first calculate the half vector, then use the cosine of the angle between the surface normal and the half vector to compute the specular light reflected.

Here we are using a shininess coefficient β\beta of 32.0 for

We assume the light colour of the light source is white, but you can definitely try other colours

The output colour

The output fragment colour is just the combination of the ambient, diffuse and specular components.

Result

We need to set the vertex shader and fragment file names in initShader() in main() to blinn.vert and blinn.frag.

With the following light source position of glm::vec3(5.0f, 5.0f, 10.0f) and eye position of glm::vec3(0.0f, 0.0f, 5.0f) in main.cpp, you will see something similar to the following:

Full Source Code

Last updated