WebGL: Odd Gouraud Shading Result

Viewed 44

I'm trying to implement Gouraud Shading with WebGL However, The result is monochromatic and looks like there is no light at all.

Here are what them look like: Gouraud Shading and Flat Shading

Below are the codes I simplified and left what seems matter to this problem:

  1. fragmentShader
<script id="fragmentShader" type="fragment">
    precision mediump float;
    varying vec4 vColor;

    void main(void) {
        gl_FragColor = vColor;
    }
</script>
  1. vertexShader
<script id="vertexShader" type="vertex">
    precision mediump float;

    attribute vec3 aVertexPosition;
    attribute vec3 aVertexNormal;
    attribute vec3 aFrontColor;

    uniform vec3 uLightPosition_1;
    uniform vec3 uAmbientColor_1;
    uniform vec3 uDiffuseColor_1;
    uniform vec3 uSpecularColor_1;
    uniform float uShininess_1;

    varying vec4 vColor;
    varying vec3 vNormal;
    varying vec3 vPosition;

vec3 calLightWeighting(vec3 ambientColor, vec3 diffuseColor, vec3 specularColor, float shininess, vec3 lightPos, vec3 vPos, vec3 normal) {
        vec3 lightDirection = normalize(lightPos - vPos);
        vec3 eyeDirection = normalize(-vPos);
        vec3 halfDirection = normalize(lightDirection + eyeDirection);
        vec3 reflectionDirection = normalize(reflect(-lightDirection, normal));

        vec3 ambient = ambientColor;
        float Kd = max(dot(normal, lightDirection), 0.0);
        vec3 diffuse = Kd * diffuseColor;
        float Ks = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);
        // I also tried: float Ks = pow(max(dot(halfDirection, normal), 0.0), shininess);
        vec3 specular = Ks * specularColor;
        return ambient + diffuse + specular;
    }

void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
    vPosition = (uMVMatrix * vec4(aVertexPosition, 1.0)).xyz;
    vNormal = normalize(uNMatrix * aVertexNormal);
    vec3 lightWeighting = calLightWeighting(uAmbientColor_1,
                                            uDiffuseColor_1,
                                            uSpecularColor_1,
                                            uShininess_1,
                                            uLightPosition_1,
                                            vPosition,
                                            vNormal);

    vColor = vec4(aFrontColor * lightWeighting, 1.0);
}
</script>

I can use the same calLightWeighting function to do the flat shading with a different normal vector. The rest parameter is the same.(just pass them to the fragment shader)

vec3 U = dFdx(vPosition);
vec3 V = dFdy(vPosition);
vec3 normal = normalize(cross(U, V));

So I wonder if the problem comes from vNormal or uNMatrix or aVertexNormal. However, I checked with console.log that I do have set up the vertex normal data.

Any ideas would be appreciated!

0 Answers
Related