Month: July 2012

OpenGL should support loading shader files

Posted on Updated on

OpenGL’s shader system is purely string based. Just pass it a couple of strings worth of shader code, compile, link, and go.

Its not actually that bad, but it gets progressively more annoying the more advanced your shader code gets. It precludes the convenient use of #include, because OpenGL has no idea where that string came from (which directory/file). All the sudden you find yourself terribly missing the ability to factor out some useful utility code into a header file, and just #include it wherever you need it.

Why am I griping about this now? Because I just wrote some code that runs through my files line by line looking for #include‘s, loading and substituting the correct included source into the original source. Honestly, it wasn’t that bad, but it still *feels* like a hack, and something I really shouldn’t have to do.

In reality I was only half done. I had rendered the shader error log meaningless, since the source it had compiled didn’t match the file I was working on. This meant I still had to read the error log generated by OpenGL whenever shader compilation failed, parse that, extract line numbers, and then figure out the correct line and file associated with the error message so that it would actually be meaningful. It works, but again, its annoying, and doesn’t seem like something OpenGL programmers should have to concern themselves with.

But what about ARB_shading_language_include?

Yes, I am aware there an extension allowing shader includes, but its all wrong. It is again string based, it introduces 6 OpenGL functions, and requires its own compilation step. A #include should be a 100% preprocessor operation. I don’t want to have to recompile my project just to include a file in my shader. And its not the way OpenGL is headed, prevailingly, more and more is being defined in the shader code itself rather than in the calling OpenGL program (which I think is great).

If its not that hard for me to hack into real #include support I imagine the OpenGL driver writers should be able to able handle it as well, and probably do a much better job of it.

So, instead of glShaderSource, I propose glShaderFile, which instead of taking in a string of shader source, it takes in a string of a shader file name, from which it extracts the directory such that the shader compiler knows where to look every time #include is used.  Optionally, it could take another string explicitly defining the shader include directory.  Alternately, another version of glShaderSource, say glShaderSourceDir could take a shader string and have a parameter to explicitly define the shader include directory.

Anyway, that’s my rant.  Its not a huge deal, but I actually think this simple addition would have a fairly large impact on the usability of glsl shaders.