<<< The smooth type qualifier     Index     Specular light >>>

14. Diffuse lighting in fragment shader


  • Vertex shader

    
    #version 130
    
    in vec4 s_vPosition;
    in vec4 s_vNormal;
    
    uniform mat4 mM;    // model matrix
    uniform mat4 mV;    // camera view matrix
    uniform mat4 mP;    // perspective matrix
    
    uniform mat4 mRotations; // all model rotations matrix
    
    uniform vec4 vLight; // direction of light
    
    out vec3 fN; // output of the normal
    out vec3 fL; // output of light vector
    
    void main () {
        
        // Rotate the normal and pass on as vec3
        fN = (mRotations*s_vNormal).xyz;
        fL = vLight.xyz;
        
        // From local, to world, to camera, to NDCs
        gl_Position = mP*mV*mM*s_vPosition;
    }
    
    
  • Fragment shader

    
    #version 130
    
    in vec3 fN;
    in vec3 fL;
    
    out vec4 fColor;
    
    void main () {
        // NOTE: We ALWAYS need to normalize the vectors after interpolation!
        vec3 N = normalize(fN);
        vec3 L = normalize(fL);
        float diffuse_intensity = max(dot(N, L), 0.0);
        vec4 light_color = vec4( 1.0, 1.0, 0.0, 1.0); // R + G = yellow
        fColor = light_color * diffuse_intensity; // yellow diffuse light
    }
    
    

<<< The smooth type qualifier     Index     Specular light >>>