Fake light with normal vector not working

I’m trying to get the normal vector into the fragment to fake a light on the shader, but the vector is always (0.0, 0.0, 0.0).

This is a basic shader to test the normal vector, but it’s a black box.

const material = new THREE.ShaderMaterial({
  vertexShader: `
    varying vec3 vNormal;
    varying vec3 vPosition;
    void main() {
      vPosition = position;
      vec3 vNormal = normal;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    varying vec3 vNormal;
    varying vec3 vPosition;
    void main() {
      
      gl_FragColor = vec4(vNormal, 1.0);
    }
  `,
});

This is the fragment shader that fakes a light using a vector and calculating the dot product of the light and the normal to display or not color, but it’s still a black box.

// same name and type as VS
varying vec3 vNormal;

void main() {

// calc the dot product and clamp
// 0 -> 1 rather than -1 -> 1
vec3 light = vec3(0.5,0.2,1.0);
    
// ensure it's normalized
light = normalize(light);

// calculate the dot product of
// the light to the vertex normal
float dProd = max(0.0, dot(vNormal, light));

// feed into our frag colour
gl_FragColor = vec4(dProd, dProd, dProd, 1.0);

}

Any thoughts?

Silly error. I was re-declaring the variable.

varying vec3 vNormal;

void main() {
    vec3 vNormal = normal;
}

so the varying was not being set.

It should be:

varying vec3 vNormal;

void main() {
   vNormal = normal;
}
1 Like