GLSL #include parser

Hey all. I’m sorry that I don’t know how to address this problem clearly in the title.

I created a parser, which parses the #include directive in GLSL shader code, finds the corresponding file, then replaces the #inlcude directive with the actual code in the file. I have several reusable structs in the file. If I copy them directly into the shader code, it works well. But the include doesn’t work. I’m sure the parser outputs the same code.

This is the parser output.

This is the shader code.

#type vertex
#version 330 core

#include <Struct.glsl>

layout (location = 0) in vec3 aPos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
	gl_Position = projection * view * model * vec4(aPos, 1.0f);

#type fragment
#version 330 core

out vec4 FragColor;

//Property Color "Color" color
uniform vec3 color;

void main()
    FragColor = vec4(color, 1.0f);

This is Struct.glsl

struct Varyings
	vec4 positionWS;
	vec3 normalWS;
	vec2 texCoords;


In what way? The text you’re including accomplishes nothing. All it does is declare a struct. A struct that is never actually used by anything.

So in what way does it “work well”?

1 Like

Yes, it accomplishes nothing but the rest of the code works just fine, a simple unlit shader. When I try to use #include, the shader doesn’t even work, even though the parser outputs the same code. Nothing appears on the screen.

OK, so what is the text you’re passing to OpenGL? And I don’t mean some printout from a console window. I mean go into a debugger and look at the actual text you’re handing to glShaderSource.

1 Like

Sorry. I shouldn’t have said work well. I meant the code worked just fine.

I did what you said and found the problem! The main function of the vertex shader disappeared.

But I don’t how this could happen. I passed what’s printed in the console directly into source, didn’t make any changes. The code looks like below. I printed out source.c_str() and main function disappeared.

unordered_map<GLenum, string> shaders;

// This is what's printed in the console.
string code;

shaders[GL_VERTEXT_SHADER] = code;

for(auto& kv : shaders)
    GLenum type = kv.first;
    const string& source = kv.second;
    GLuint shader = glCreateShader(type);
    // Here
    const GLchar* shaderSource = source.c_str();

    glShaderSource(shade, 1, &shaderSource, 0);

Thank you sir, problem solved.
After reading Struct.glsl, I use

string& string::insert (size_type idx, const string& str)

to insert the content.

I changed it to

string& string::insert (size_ type idx, const char* cstr)

and it worked.
I think when I use string, I accidentally insert a ‘\0’ which makes c_str() end unexpectedly. I’m not sure, I’m still very new to C++. Appreciate your help sir.