I currently have this vertex shader:
#version 130
in vec3 position;
in vec2 textureCoords;
in vec3 normal;
out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
uniform vec3 lightPosition;
void main(void){
surfaceNormal = normal;
toLightVector = vec3(1, 100, 1);
gl_Position = ftransform(); #Yes, I use the fixed-function pipeline. Please don't kill me.
pass_textureCoords = textureCoords;
}
This works fine, but then when I add this:
#version 130
in vec3 position;
in vec2 textureCoords;
in vec3 normal;
out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
uniform vec3 lightPosition;
void main(void){
vec3 pos = position; #Completely USELESS added line
surfaceNormal = normal;
toLightVector = vec3(1, 100, 1);
gl_Position = ftransform();
pass_textureCoords = textureCoords;
}
The whole object just turns black (Or green sometimes, but you get the idea - It isn't working).
Expected behaviour: Actual behaviour: (The terrain and water are rendered without any shaders, hence why they are not changed)
It's as if the variable "position" is poisonous - If I use it anywhere, even for something useless, my shader simply does not work correctly.
Why could this be happening, and how could I fix it?
You're running into problems because you use both the fixed function position attribute in your vertex shader, and a generic attribute bound to location 0. This is not valid.
While you're not using the fixed function gl_Vertex
attribute explicitly, the usage is implied here:
gl_Position = ftransform();
This line is mostly equivalent to this, with some additional precision guarantees:
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
But then you are also using a generic attribute for the position:
in vec3 position;
...
vec3 pos = position;
If you assign location 0 for this generic attribute, the result is an invalid shader program. I found the following on page 94 of the OpenGL 3.3 Compatibility Profile spec, in section "2.14.3 Vertex Attributes":
LinkProgram will also fail if the vertex shaders used in the program object contain assignments (not removed during pre-processing) to an attribute variable bound to generic attribute zero and to the conventional vertex position (gl_Vertex).
To avoid this problem, the ideal approach is of course to move away from using fixed function attributes, and adopt the OpenGL Core Profile. If that is outside the scope of the work you can tackle, you need to at least avoid assigning location 0 to any of your generic vertex attributes. You can either:
glBindAttribLocation()
.glGetAttribLocation()
to get the automatically assigned locations after you link the program.