0
votes

I have a problem while getting an uniform from a shader. The line:

int u = GL20.glGetUniformLocation(program, uniform);

is used to check if the uniform defined by the string uniform is in the shader.

Here is an example check code:

System.out.println(GL20.glGetUniformLocation(1, "transformationMatrix")==0);
System.out.println(GL20.glGetUniformLocation(1, "projectionMatrix")==0);

And the result:

false
true

Here it comes the weird thing: The vertex shader code is the following:

#version 330

layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 tex;
layout (location = 2) in vec3 nor;
layout (location = 3) in vec3 col;

uniform mat4 projectionMatrix;
uniform mat4 transformationMatrix;

out vec3 normal;

void main(){

    normal = nor;
    gl_Position = projectionMatrix * vec4(pos, 1);
} 

I have tested renaming the uniform, removing the other one, but the only one uniform OpenGL seems to recognize is the "projectionMatrix" one.

Enviroment: Java with lwjgl OpenGl in linux with mesa 10.4.0 (Doesn't work on Windows either)

2

2 Answers

4
votes

The GLSL compiler is allowed to strip unused variables from the emitted executable shader, as an optimization (fewer registers used etc.). If the transformationMatrix uniform is used to compute the return value of the shader, it will then be kept in the shader, and the error will disappear.

This is not a "hard" error, feel free to ignore it. You may encounter it especially when you change the GLSL code for debugging purpose.

3
votes

glGetUniformLocation() returns -1 if the uniform was not found. From the man page:

This function returns -1 if name does not correspond to an active uniform variable in program or if name starts with the reserved prefix "gl_".

So the error test needs to be:

System.out.println(GL20.glGetUniformLocation(1, "transformationMatrix") == -1);
System.out.println(GL20.glGetUniformLocation(1, "projectionMatrix") == -1);

As suggested in another answer, it is true that unused uniforms can be eliminated when the shader is compiled/linked. But this is not what you're observing in this case. 0 is a valid uniform location.