OpenGL - Problems getting shaders to compile - c++

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.

Related

Cant access vec4 array in GLSL

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.

Why does my GLSL shader fail compilation with no error message?

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.

GLSL Shader Program Randomly Fails to Compile

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.

Transforming glsl 150 to 120

I have a couple of examples that I want to run on my PC. The problem is that they're written with glsl target 150 and my PC only supports version 120. I'm pretty sure that the program itself is simple enough not to require any extended functionality of OpenGL 3.1. I have found some information on what steps should be taken to transform glsl(f.e. changing in to attribute, out to varying) but it's still not compiling(is it actually possible to somehow get a meaningful error message out of this?).
original .vert
#version 150
in vec2 in_Position;
in vec3 in_Color;
out vec3 ex_Color;
void main(void) {
gl_Position = vec4(in_Position.x, in_Position.y, 0.0, 1.0);
ex_Color = in_Color;
}
original .frag
#version 150
precision highp float;
in vec3 ex_Color;
out vec4 gl_FragColor;
void main(void) {
gl_FragColor = vec4(ex_Color,1.0);
}
changed .vert
#version 120
attribute vec2 in_Position;
attribute vec3 in_Color;
varying vec3 ex_Color;
void main(void) {
gl_Position = vec4(in_Position.x, in_Position.y, 0.0, 1.0);
ex_Color = in_Color;
}
changed .frag
#version 120
precision highp float;
attribute vec3 ex_Color;
void main(void) {
gl_FragColor = vec4(ex_Color,1.0);
}
So can anyone spot a problem here?
To get the compile/link error messages, you need to use the commands glGetShaderInfoLog for shaders, and glGetProgramInfoLog for programs.
These will tell you what your particular errors are.
Just taking a stab at what the error might be, you're declaring an attribute input in the fragment shader, which I believe should be a varying. Attributes are for data->vertex shader, and varyings are for vertex shader -> fragment shader.
The glsl 120 spec also mentions that precision qualifier is "reserved for future use", so it may not be applicable to version 120. You can probably leave it out.
But you should still get familiar with the infolog functions regardless, you'll definitely need them eventually.
You can get the compile errors by retrieving the "info log":
GLuint nVertexShader, nPixelShader; // handles to objects
GLint vertCompiled, fragCompiled; // status values
GLint linked;
glCompileShader(nVertexShader);
glGetShaderiv(nVertexShader, GL_COMPILE_STATUS, &vertCompiled);
if vertCompiled (or fragCompile) == 0, do this to see why:
int infologLength = 0;
int charsWritten = 0;
glGetShaderiv(nVertexShader, GL_INFO_LOG_LENGTH, &infologLength);
if (infologLength > 0)
{
GLchar* infoLog = (GLchar *)malloc(infologLength);
if (infoLog == NULL)
{
printf( "ERROR: Could not allocate InfoLog buffer");
exit(1);
}
glGetShaderInfoLog(nVertexShader, infologLength, &charsWritten, infoLog);
printf( "Shader InfoLog:\n%s", infoLog );
free(infoLog);
}
You can do the same with linking, just check for linked == 0 and retrieve the log as above:
glLinkProgram(m_nProgram);
glGetProgramiv(m_nProgram, GL_LINK_STATUS, &linked);
precision highp float;
That is not legal in GLSL 1.20. I don't even know why it was put in the 1.50 shader anyway, since the precision qualifiers only do useful things in GLSL ES, and you can't share 1.50 shaders with GLSL ES.

Compiling OpenGL shaders causes syntax errors

I have two simple shaders (vertex and fragment)
Vertex Shader
#version 330 core
//=============================================
//---[Structs/Vertex Data]---------------------
//=============================================
layout(location = 0) in vec3 vertexPosition_modelspace;
//=============================================
//---[Variables]-------------------------------
//=============================================
uniform mat4 projection;
uniform mat4 view;
//=============================================
//---[Vertex Shader]---------------------------
//=============================================
void main()
{
gl_Position = projection * view * vertexPosition_modelspace;
}
Fragment Shader
#version 330 core
//=============================================
//---[Output Struct]---------------------------
//=============================================
out vec3 colour;
//=============================================
//---[Fragment Shader]-------------------------
//=============================================
void main()
{
colour = vec3(1, 0, 0);
}
I am trying to compile them and I get the following error
error C0000: syntax error, unexpected $undefined, expecting "::" at token "undefined"
I believe this may have something to do with the way I am reading the files. Here is an example for the vertex shader file
std::string VertexShaderCode = FindFileOrThrow(vertex_file_path);
std::ifstream vShaderFile(VertexShaderCode.c_str());
std::stringstream vShaderData;
vShaderData << vShaderFile.rdbuf();
vShaderFile.close();
The file is then compiled using
char const *VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
How can I efficiently read in the files and avoid these errors?
EDIT:
Correct compile:
const std::string &shaderText = vShaderData.str();
GLint textLength = (GLint)shaderText.size();
const GLchar *pText = static_cast<const GLchar *>(shaderText.c_str());
glShaderSource(VertexShaderID, 1, &pText, &textLength);
glCompileShader(VertexShaderID);
VertexShaderCode is your filename, not the shader string. That's still in vShaderData. You need to copy the string out of vShaderData, and feed it into glShaderSource.