When I try to compile this GLSL code in OpenGL 4.0 I get error 1282
Vertex shader:
#version 330 core
layout(location = 0) in vec2 aPos;
uniform mat4 model[100];
uniform mat4 projection;
out int instanceID;
void main()
{
instanceID = gl_InstanceID;
gl_Position = projection * model[gl_InstanceID] * vec4(aPos.x, aPos.y, 0.0, 1.0);
}
Fragment shader:
#version 330 core
in int instanceID;
out vec4 FragColor;
uniform vec4 color[100];
void main()
{
FragColor = color[instanceID];
}
The code is regular ShaderProgram creation because I get the error before drawing or anything like that but just in case here is the code:
unsigned int vertex, fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
std::string vShaderCode = ReadEntireTextFile(vertPath);
const char* c_vShaderCode = vShaderCode.c_str();
glShaderSource(vertex, 1, &c_vShaderCode, NULL);
glCompileShader(vertex);
std::string fShaderCode = ReadEntireTextFile(fragPath);
fragment = glCreateShader(GL_FRAGMENT_SHADER);
const char* c_fShaderCode = fShaderCode.c_str();
glShaderSource(fragment, 1, &c_fShaderCode, NULL);
glCompileShader(fragment);
// shader Program
m_RendererID = glCreateProgram();
glAttachShader(m_RendererID, vertex);
glAttachShader(m_RendererID, fragment);
glLinkProgram(m_RendererID);
// delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(vertex);
glDeleteShader(fragment);
glUseProgram(m_RendererID);
I know for sure that the error is because of instanceID because it worked when the shader didn't have that. but I tried to find where the problem is exactly with no luck.
UPDATE:
Made sure shaders were compiled successfully. and turns out they are compiled successfully.
I was able to pinpoint where the error occurs and it was the glUseProgram funtion.
I think the error is because of instanceID because when I change:
FragColor = color[instanceID];
to
FragColor = color[0];
the program works.
UPDATE(2):
I solved the problem.
Turns out I had 2 problems one being that I had too many components and I fixed that thanks to one of the answers alerting me.
The other was that I can't put uniforms directly in the fragment shader which I thought you could do.So I put the colors in the vertex shader and passed the one color I needed for the fragment shader.
Thanks for the help!
uniform mat4 model[100];
That is way outside of what is guaranteed by the spec. The limit here is GL_MAX_VERTEX_UNIFORM_COMPONENTS, which the spec guarantees to be at least 1024. Since a mat4 consumes 16 components, that's 64 matrices at most. Now your particular limit might be higher, but you also have the other uniforms in your program, like color[100].
(from comments):
It does not return anything for both fragment and vertex shaders and glGetShaderiv(shader, GL_COMPILE_STATUS, &output); returns true for both shaders.
But that does not imply that the program object linked successfully. Such ressource limits are usually enforced during linking.
I'm pretty sure program is an object created by openGL successfully, I'm not really sure about the others though. you see if i change the fragment shader main function to FragColor = color[0]; it will work so the issue is with instanceID I think.
That conclusion does not follow. If you write color[0], it will optimize your vec4r[100] array to vec4[1], and you might get below your particular limit.
Related
I'm building a game using OpenGL and C++. I'm using GLFW and GLAD. I'm currently in the process of setting up simple shaders, but I'm completely roadblocked by a compilation problem. In a nutshell, shader compilation fails with no error message.
Here's my vertex shader (it's meant to draw 2D images and text):
#version 330 core
layout (location = 0) in vec2 vPosition;
layout (location = 1) in vec2 vTexCoords;
layout (location = 2) in vec4 vColor;
out vec4 fColor;
out vec2 fTexCoords;
uniform mat4 mvp;
void main()
{
vec4 position = mvp * vec4(vPosition, 0, 1);
position.y *= -1;
gl_Position = position;
fColor = vColor;
fTexCoords = vTexCoords;
}
And here's the relevant code to create the shader, load the shader source, compile the shader, and check for errors.
GLuint shaderId = glCreateShader(GL_VERTEX_SHADER);
std::string source = FileUtilities::ReadAllText(Paths::Shaders + filename);
GLchar const* file = source.c_str();
GLint length = static_cast<GLint>(source.size());
glShaderSource(shaderId, 0, &file, &length);
glCompileShader(shaderId);
GLint status;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint logSize = 0;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);
std::vector<GLchar> message = std::vector<GLchar>(logSize);
glGetShaderInfoLog(shaderId, logSize, nullptr, &message[0]);
glDeleteShader(shaderId);
std::cout << std::string(message.begin(), message.end());
}
Using that code, logSize is returned as 1, meaning that I'm unable to access the error message provided by GL. From what I can tell, the message doesn't exist at all. I've already seen the question posted here, in which the issue was a missing call to glCompileShader. As you can see, my code does call that function.
In attempting to solve this problem, I've already confirmed a few things.
My shader source (a string) is being read correctly. The source is a single string that, as far as I can tell, exactly matches the actual shader file.
There are no casting issues from the string source to GLchar const* or GLint (the variables file and length). Both look correct.
If I artificially inflate the value of logSize (to, say, 1000), the resulting message is nothing but zeroes. No error message exists.
I am calling glfwInit() and related functions before reaching this point in the code. Querying glGetString(GL_VERSION) does correctly return the target version (3.3.0).
Does anyone know how to fix this? As I said, my progress is completely blocked since I can't render anything (2D or 3D) without working shaders.
Thank you!
The problem is that you never upload any shader source to the shader.
The second parameter in this line:
glShaderSource(shaderId, 0, &file, &length);
tells OpenGL to load 0 code strings to the shader (nothing). Change this to 1, and it should work.
I'm writing an application using OpenGL 4.3 and GLSL and I need the shader to do basic UV mapping. The problem is that GLSL compiler seems to be optimising-out the UV coordinates. I cannot access them from the application side of things.
Vertex shader:
#version 330 core
uniform mat4 projection;
layout (location = 0) in vec4 position;
layout (location = 1) in vec2 uvCoord;
out vec2 texCoord;
void main(void)
{
texCoord = uvCoord;
gl_Position = position;
}
Vertex shader:
#version 330 core
in vec2 texCoord;
out vec4 color;
uniform sampler2D tex;
void main(void)
{
color = texture2D(tex, texCoord);
}
Both the vertex and fragment shader compile and link without errors, but when I call the attributes using the following code:
GLint effectPositionLocation = glGetAttribLocation(effect->getEffect(), "position");
GLint effectUVLocation = glGetAttribLocation(effect->getEffect(), "uvCoord");
I get the 0 for the position and -1 for the uvCoord, so I can only assume that the uvCoord has been optimised out even though I am using it to pass it from the vertex shader to the fragment shader.
The result is that the geometry is displayed but only in black, no texture mapping.
I have Written similar applications in Direct3D and HLSL with no problem of attributes being optimised out. I'm thinking that it is something simple that I am forgetting or not doing but have not found out what.
Replace the 'texture2D' with 'texture', and your attribute will be used.
Bad GLSL compiler: it should not compile your shader since texture2D is not available in core profile.
EDIT: You may have forgotten to call glEnableVertexAttribArray(1); after setting your glVertexAttribPointers.
I wrote a pair of shaders to display the textures as greyscale instead of full color. I used these shaders with libGDX's built in SpriteBatch class and it worked. Then when I tried to use it with the built in SpriteCache class it didn't work. I looked at the SpriteCache code and saw that it set some different uniforms that I tried to take into account but I seem to have gone wrong somwhere.
The SpriteCache class in libGDX sets the following uniforms:
customShader.setUniformMatrix("u_proj", projectionMatrix);
customShader.setUniformMatrix("u_trans", transformMatrix);
customShader.setUniformMatrix("u_projTrans", combinedMatrix);
customShader.setUniformi("u_texture", 0);
This is my vertex shader:
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_proj;
uniform mat4 u_projTrans;
uniform mat4 u_trans;
varying vec4 v_color;
varying vec2 v_texCoords;
void main() {
v_color = a_color;
v_texCoords = a_texCoord0;
gl_Position = a_position* u_proj * u_trans;
}
and this is the fragment shader:
varying vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform u_projTrans;
void main() {
vec4 color = texture2D(u_texture, v_texCoords).rgba;
float gray = (color.r + color.g + color.b) / 3.0;
vec3 grayscale = vec3(gray + 0* u_projTrans[0][0]);
gl_FragColor = vec4(grayscale, color.a);
}
The error I get is:
Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: no uniform with name 'u_proj' in shader
...
com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)ackends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
I guess do any of you guys know why this isn't working? There is a uniform with the name u_proj.
Thank you all!
What Reto Koradi said was true I had forgotten to put a mat4 tag before u_projTrans, that helped me.
Then what Tenfour04 said was a huge help too! I hadn't known about:
if (!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog());
What helped me most in the long run was finding that glsl, when compiling, would do away with unused imports and that if you weren't able to trick the compiler into thinking that unused imports were used being used the shader would compile and then crash on runtime.
In libgdx there is a static "pedantic" variable that you can set. If it is set to false the application won't crash if variables are sent to the shader that the shader isn't using, they will simply be ignored. The code in my libgdx program looked something like this:
ShaderProgram.pedantic = false;
Thanks for your help all! I hope this can help someone in the future
Make sure that you check the success of your shader compilation/linking. Your fragment shader will not compile:
uniform u_projTrans;
This variable declaration needs a type. It should be:
uniform mat4 u_projTrans;
You can use the following calls to test for errors while setting up your shader programs:
glGetShaderiv(shaderId, GL_COMPILE_STATUS, ...);
glGetShaderInfoLog(shaderId, ...);
glGetProgramiv(programId, GL_LINK_STATUS, ...);
glGetProgramInfoLog(programId, ...);
I'm experiencing a strange behaviour in my OpenGL application. I generate a number of GLSL programs during the initialization of the program. The shader programs are read from text files and the programs are compiled and linked. However, I randomly encounter compilation errors for one of the shader programs (a pass-through vertex shader). I cannot understand why the program loads perfectly fine and the shader program successfully compiles several times but fails to do in other times!
Here is the shader code:
#version 330
// vertex position in the model space
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec2 inTexCoord;
// will be interporlated for each fragment
smooth out vec2 vTexCoord;
// uniforms
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
void main(void) {
gl_Position = projectionMatrix * modelViewMatrix * vec4(inPosition, 1.0);
vTexCoord = inTexCoord;
}
And here is the code for compiling the shader (passThroughVertShader is a QString):
this->passThroughVertShader = glCreateShader(GL_VERTEX_SHADER);
const char *passThroughVertShaderCodeC = passThroughVertShaderCode.toStdString().c_str();
sourceCode = passThroughVertShaderCodeC;
glShaderSource(this->passThroughVertShader, 1, &sourceCode, NULL);
glCompileShader(this->passThroughVertShader);
glGetShaderiv(this->passThroughVertShader, GL_COMPILE_STATUS, &isCompiled);
if(isCompiled == GL_FALSE)
{
qDebug("ERROR compiling pass-through vertex shader..");
exit(-1);
}
glAttachShader(this->shaderProgram, this->passThroughVertShader);
And the function that loads it:
QString MyClass::readShaderFile(const QString &filename) {
QString content;
QFile file(filename);
if (file.open(QIODevice::ReadOnly)) {
QTextStream tStream(&file);
content = tStream.readAll();
}
return content;
}
Update:
Following Andon's suggestion, I double checked and I wasn't checking the log after failure. Here is what the log says:
Error: 0(17) : error C0000: syntax error, unexpected '!', expecting "::" at token "!"
Ok, answering myself here. Thanks to AndonM.Coleman for pointing out that I should check the error log. The output was not clear, but it lead me to another SO question that shed some light on a bug I had in the code. Apparently I was doing the right thing for compiling all other shaders in the program and somehow forgot one line when I was writing the code for this one. What I should have been doing was the following:
string passThroughVertShaderCodeS = passThroughVertShaderCode.toStdString();
const char *passThroughVertShaderCodeC = passThroughVertShaderCodeS.c_str();
In short, the toStdString() method was returning a temporary copy of the buffer. Since I'm calling c_str() on that temporary copy which gets destroyed after that line, that pointer becomes invalid. I'm not sure why it occasionally succeeded though.
I have the following piece of shader code that works perfectly with GLSL #130, but I would like to convert it to code that works with version #330 (as somehow the #130 version doesn't work on my Ubuntu machine with a Geforce 210; the shader does nothing). After several failed attempts (I keep getting undescribed link errors) I've decided to ask for some help. The code below dynamically changes the contrast and brightness of a texture using the uniform variables Brightness and Contrast. I have implemented it in Python using PyOpenGL:
def createShader():
"""
Compile a shader that adjusts contrast and brightness of active texture
Returns
OpenGL.shader - reference to shader
dict - reference to variables that can be passed to the shader
"""
fragmentShader = shaders.compileShader("""#version 130
uniform sampler2D Texture;
uniform float Brightness;
uniform float Contrast;
uniform vec4 AverageLuminance;
void main(void)
{
vec4 texColour = texture2D(Texture, gl_TexCoord[0].st);
gl_FragColor = mix(texColour * Brightness,
mix(AverageLuminance, texColour, Contrast), 0.5);
}
""", GL_FRAGMENT_SHADER)
shader = shaders.compileProgram(fragmentShader)
uniform_locations = {
'Brightness': glGetUniformLocation( shader, 'Brightness' ),
'Contrast': glGetUniformLocation( shader, 'Contrast' ),
'AverageLuminance': glGetUniformLocation( shader, 'AverageLuminance' ),
'Texture': glGetUniformLocation( shader, 'Texture' )
}
return shader, uniform_locations
I've looked up the changes that need to made for the new GLSL version and tried changing the fragment shader code to the following, but then only get non-descriptive Link errors:
fragmentShader = shaders.compileShader("""#version 330
uniform sampler2D Texture;
uniform float Brightness;
uniform float Contrast;
uniform vec4 AverageLuminance;
in vec2 TexCoord;
out vec4 FragColor;
void main(void)
{
vec4 texColour = texture2D(Texture, TexCoord);
FragColor = mix(texColour * Brightness,
mix(AverageLuminance, texColour, Contrast), 0.5);
}
""", GL_FRAGMENT_SHADER)
Is there anyone that can help me with this conversion?
I doubt that raising the shader version profile will solve any issue. #version 330 is OpenGL-3.3 and according to the NVidia product website the maximum OpenGL version supported by the GeForce 210 is OpenGL-3.1, i.e. #version 140
I created no vertex shader cause I didn't think I'd need one (I wouldn't know what I should make it do). It worked before without any vertex shader as well.
Probably only as long as you didn't use a fragment shader or before you were attempting to use a texture. The fragment shader needs input variables, coming from a vertex shader, to have something it can use as texture coordinates. TexCoord is not a built-in variable (and with higher GLSL versions any builtin variables suitable for the job have been removed), so you need to fill that with value (and sense) in a vertex shader.
the glGetString(GL_VERSION) on the NVidia machine reads out OpenGL version 3.3.0. This is Ubuntu, so it might be possible that it differs with the windows specifications?
Do you have the NVidia propriatary drivers installed? And are they actually used? Check with glxinfo or glGetString(GL_RENDERER). OpenGL-3.3 is not too far from OpenGL-3.1 and in theory OpenGL major versions map to hardware capabilities.