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.
Related
I'm trying to learn how to use tesselation to render simple polygons, and for a starter I'm trying to write a simple program that essentially would just draw whatever vertices it's given, without any extra logic. My three shaders compile without error, but when I try to apply the program OpenGL returns error 1282. Based on the documentation for glUseProgram my best guess is that OpenGL is in a state where the program cannot be used, but I'm not able to tell why. If I don't include the TES in the program my code runs just fine, so I'm sure I'm not trying to apply the wrong program ID.
Since I know with fairly good confidence that my vertex and fragment shader are working correctly, the issue must be with the TES, which in my eyes will only put out the control points as vertices.
Is it not possible to simply pass control points through the shader as vertices?
My Tesselation Evaluation Shader:
#version 440 core
layout(triangles, equal_spacing, ccw) in;
in vec4 positionIn[];
void main()
{
gl_Position = positionIn[0];
}
Vertex Shader:
#version 440 core
layout(location = 0) in vec4 position;
uniform mat4 u_MVP;
void main()
{
gl_Position = u_MVP * position;
}
Fragment Shader:
#version 440 core
layout(location = 0) out vec4 colour;
uniform vec4 u_Colour;
void main()
{
colour = u_Colour;
}
Rest of the code that handles the compilation and setup:
int compileShader(unsigned int type, const std::string& source)
{
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
char* message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(id, length, &length, message);
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
return id;
}
void setUpProgram()
{
unsigned int program = glCreateProgram();
unsigned int vs = compileShader(GL_VERTEX_SHADER, vertexShader);
unsigned int fs = compileShader(GL_FRAGMENT_SHADER, fragmentShader);
unsigned int es = compileShader(GL_TESS_EVALUATION_SHADER, tesselationEvaluationShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glAttachShader(program, es);
glLinkProgram(program);
glValidateProgram(program);
GLenum error = glGetError();
while (error != GL_NO_ERROR)
{
std::cout << "Error: " << error << std::endl;
GLenum error = glGetError();
}
glUseProgram(program);
error = glGetError();
std::cout << "Error: " << error << std::endl;
}
There are two problems.
The first is that the vertex shader output is not being consumed by the tessellation evaluation shader. The VS outputs gl_Position, but the TES doesn't read gl_Position. It instead reads a user-defined input positionIn, which has no linkage to the value of gl_Position. Indeed, it has no value at all, and your shader linking process would have told you that if you checked whether your program successfully linked.
The corresponding TES input for the gl_Position output is, cleverly named, gl_Position. However, since this is the same name as the output you intend to write to, it is defined within an input interface block gl_PerVertex. So if you want to access it, you need to declare this interface block appropriately:
in gl_PerVertex
{
vec4 gl_Position;
} gl_in[gl_MaxPatchVertices];
You can then use gl_in[ix].gl_Position to access the position for that vertex. Speaking of array indexing...
The second problem is that [0] is the wrong index. The job of the TES is to compute the attributes for a vertex within the tessellated abstract patch. To do that job, the TES is given all of the vertices for the patch. So each TES invocation for a patch gets the same set of inputs, in the same order.
So doing gl_in[0].gl_Position would yield the same value for each vertex in the patch. That's a triangle with zero area, and thus isn't helpful in displaying anything.
The only thing the TES invocations get which are different is the input value vertexTexCoord, which is the coordinate of this TES invocation within the abstract patch. This is a vec3, and for triangle tessellation, represents the barycentric coordinate of the vertex within the abstract patch.
So you need to convert this vec3 into an index. If you aren't doing any tessellation at all, then the barycentric coordinate will have one of the values at 1.0, with the other values being zero. So you can use that to tell you which index you should use.
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.
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'm trying to compile a shader program in OpenGL 3.2, but I'm getting a strange linking error.
After creating the vertex and fragment shaders compiling and attaching them, I try to link them into a program but I get the following infolog error:
ERROR: Compiled vertex shader was corrupt.
ERROR: Compiled fragment shader was corrupt.
I have absolutely no idea what it means and the only thing I could find on google was to ignore it. However, when I glUseProgram() it I get an invalid operation, so I can't just ignore this error.
Moreover, I just updated to XCode 5 and the very same code/shader source was working. Don't know how it can be related though..
Edit: shader source
Vertex:
#version 150
in vec3 position;
uniform mat4 worldMatrix;
uniform float time;
out vec3 outPos;
void main(){
gl_Position = worldMatrix*vec4(position, 1.0);
outPos = position;
}
Fragment:
#version 150
out vec4 outColor;
uniform float time;
uniform float red;
uniform float green;
uniform float blue;
void main(){
outColor=vec4(red, green, blue,1.0);
}
Got it to work.
At first I rewrote the shaders with another editor (text mate) and then it worked sometimes. Then I made sure that it was properly null terminated and it worked every time.
Maybe somehow there were non-printing characters like Andon M. Coleman suggested.
I had the same issue, and discovered that if you use the ' std::stringstream buffer' to read the file, as many code examples on the web use, the method .str().c_str() to get a *ptr needed for glShaderSource, the pointer gets deleted, meaning, you get random linker errors. Here is the work around I created...
int shaderFromFile(const std::string& filePath, GLenum shaderType) {
//open file
std::ifstream f;
f.open(filePath.c_str(), std::ios::in);
if(!f.is_open()){
throw std::runtime_error(std::string("Failed to open file: ") + filePath);
}
//read whole file into stringstream buffer
std::stringstream buffer;
buffer << f.rdbuf();
buffer << "\0";
f.close();
// need to copy, as pointer is deleted when call is finished
std::string shaderCode = buffer.str().c_str();
//create new shader
int ShaderID = glCreateShader(shaderType);
//set the source code
const GLchar* code = (const GLchar *) shaderCode.c_str();
glShaderSource(ShaderID, 1, &code, NULL);
//compile
glCompileShader(ShaderID);
//throw exception if compile error occurred
GLint status;
glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &status);
std::cout << "Status from compile:" << status << "\r\n";
if (status == GL_FALSE) {
std::string msg("Compile failure in shader:\n");
GLint infoLogLength;
glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
char* strInfoLog = new char[infoLogLength + 1];
glGetShaderInfoLog(ShaderID, infoLogLength, NULL, strInfoLog);
msg += strInfoLog;
delete[] strInfoLog;
glDeleteShader(ShaderID); ShaderID = 0;
throw std::runtime_error(msg);
}
return ShaderID;
}
Finally isolated the issue of my shader not being able to be used to it failing to compile.
Here is my shader loading routine. The first part reads in the shader:
void GLSLShader::LoadFromFile(GLenum whichShader, const string filename)
{
ifstream fp;
// Attempt to open the shader
fp.open(filename.c_str(), ios_base::in);
// If the file exists, load it
if(fp)
{
// Copy the shader into the buffer
string buffer(std::istreambuf_iterator<char>(fp), (std::istreambuf_iterator<char>()));
// Debug output to show full text of shader
errorLog.writeSuccess("Shader debug: %s", buffer.c_str());
LoadFromString(whichShader, buffer);
}
else
{
errorLog.writeError("Could not load the shader %s", filename.c_str());
}
}
After it has loaded it into a string, it sends it to be loaded:
void GLSLShader::LoadFromString(GLenum type, const string source)
{
// Create the shader
GLuint shader = glCreateShader(type);
// Convert the string
const char * ptmp = source.c_str();
glShaderSource(shader, 1, &ptmp, NULL);
// Compile the shader
glCompileShader(shader);
// Check to see if the shader has loaded
GLint status;
glGetShaderiv (shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
glGetShaderInfoLog (shader, infoLogLength, NULL, infoLog);
errorLog.writeError("could not compile: %s", infoLog);
delete [] infoLog;
}
_shaders[_totalShaders++]=shader;
}
I am getting the debug output "could not compile: " and it seems that the error buffer is empty. This has been driving me crazy for the past 3 days. Does anyone see my error?
Here are the very simple shaders:
#version 330
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;
smooth out vec4 theColor;
void main()
{
gl_Position = position;
theColor = color;
}
#version 330
smooth in vec4 theColor;
out vec4 outputColor;
void main()
{
outputColor = theColor;
}
UPDATE
It looks like for some reason there is crap being added to the end of the shader in memory. I am not sure why. I have tried reading it in to a char* and a string. Here is the output:
<-!-> Shader: #version 330
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;
smooth out vec4 theColor;
void main()
{
gl_Position = position;
theColor = color;
}
n
<-!-> Shader: #version 330
smooth in vec4 theColor;
out vec4 outputColor;
void main()
{
outputColor = theColor;
}
nts/Resources
Notice the 'n' at the end of the first shader and the 'nts/Resources' at the end of the second one. Any idea why?
ANOTHER UPDATE
The crap at the end was caused by an extra line at the end. I removed it and it is back to outputting the correct shader text. Still no luck thought with compiling.
I am at a loss here. The Superbible has their extensive libraries that are unoptimized and I don't need. There doesn't seem to be a damn decent shader compiler for Mac. I really don't mind how simple it is. It just needs to work with shaders. Does anyone have an example?
You're calling glShaderSource without supplying the length of each string in the sources array. Hence the string supplied is assumed to be terminated by a null byte ('\0'). The way you're reading the file into memory does not terminate the shader source with an additional null byte. So the GLSL compiler will read beyond the end of the shader source into random memory, where it finds… garbage.
Solution: Either add a terminating null byte, or supply the shader text lengths parameter.