Search code examples
opengl-esglslshaderwebglwebgl2

getUniformLocation return null


I have a uniform in my fragment shader and when I try to get the value of the location of the uniform, it returns null.

I checked the spelling and I don't find any spelling error and this uniform is also used in the shader code.

My error is:

error in getUniformLocation([object WebGLProgram], materialAmbient): uniform 'materialAmbient' does not exist in WebGLProgram("unnamed")

enter image description here

This is my code in WebGL to get a uniform location.

let materialAmbientLocation = gl.getUniformLocation(programScene,"materialAmbient");

let materialDiffuseLocation = gl.getUniformLocation(programScene,"materialDiffuse");

let materialSpecularLocation = gl.getUniformLocation(programScene,"materialSpecular");

let shininessLocation = gl.getUniformLocation(programScene, "shininess");

let ambiemtLightLocation = gl.getUniformLocation(programScene, "ambientLight");

let diffuseLightLocation = gl.getUniformLocation(programScene, "diffuseLight");

let specularLightLocation = gl.getUniformLocation(programScene,"specularLight");

My fragment Shader:

my glsl

const fsSkybox = `#version 300 es

 precision highp float;

 in vec3 texPosition;
 in vec3 v_normal; 
 in vec3 f_position;

 out vec4 outColor;

 // uniform samplerCube u_SkyTexture;

 uniform vec3 materialAmbient;

 uniform vec3 emission;

 uniform vec3 materialDiffuse;
 uniform vec3 materialSpecular;
 uniform float shininess;

 uniform vec3 lightDirection;
 uniform vec3 cameraPosition;

 uniform vec3 ambientLight;
 uniform vec3 diffuseLight;
 uniform vec3 specularLight;

 void main(){

  vec3 f_normal = normalize(v_normal);

  vec3 effectiveAmbient = ambientLight*materialAmbient;

  vec3 f_lightDirection = normalize(lightDirection);

  float lambertCofficient = max(dot(f_lightDirection, f_normal), 0.0);
  vec3 effectiveDiffuse = lambertCofficient*materialDiffuse*diffuseLight;

  vec3 surfacetoView = normalize(cameraPosition - f_position);
  vec3 halfVector = lightDirection + surfacetoView;
  float specular = dot(halfVector, f_normal);
  vec3 effectiveSpecular = materialSpecular*pow(specular, shininess); 

  outColor = vec4(emission + effectiveDiffuse + effectiveSpecular, 1.0);

  // outColor = texture(u_SkyTexture, texPosition);
  // outColor = vec4(0.0, 1.0, 0.0, 1.0);     
  } 
`;

Solution

  • The uniforms materialAmbient, ambientLight and specularLight are not "used" in the shader program. They are not required to calculate the output outColor (Actually materialAmbient are ambientLight use to calculate effectiveAmbient. effectiveAmbient, however is not used).
    The compiler and linker optimize the program and removes unnecessary calculations and unnecessary variables. Therefore this variables become no active program resource and you cannot get the resource index (uniform location) for this variables.