How to reuse code between different shaders


#1

Hello, I’ve a library used in different fragment shaders. Is there a way to include it? For now I’m copying and paste its content every time i need it but I’m ending up with files with an high level of verbosity.

In the javascript world there is this https://github.com/glslify/glslify that it is handy for structuring modular application, I wonder if something similar can be used also in OF.


#2

you may have a centralized repository for your library and include the library files in your shaders
the path needs to be relative to the shader file which include the library file :

for instance, if we have a noise library file, we can include it in our shader with the following line :

#pragma include "../../../library/noise.glsl"

#3

I’ve tried this on macos successfully but it didn’t work on windows10. No idea if it works for linux.


#4

it seems to only work on unix based systems since it works on linux too


#5

Does it works just with absolute paths?


#6

No, it works with relatives paths. It does not work obviusly with ofxAutoReloadedShader, that’s why I was having an error. Thanks!


#7

Hi @edapx!
Are you using ofxAutoReloadedShader with OF 0.9 or above? Because I’m trying now with OF 0.10 and I have a Poco issue.
I found here that OF doesn’t use Poco anymore:

so I tried to change “getLastModified” method in that way:

std::time_t ofxAutoReloadedShader::getLastModified( ofFile& _file )
{
	if( _file.exists() )
	{
//    Poco::File& pocoFile    = _file.getPocoFile();
//    Poco::Timestamp timestamp  = pocoFile.getLastModified();
    std::time_t fileChangedTime = std::filesystem::last_write_time(_file);
		return fileChangedTime;
	}
	else
	{
		return 0;
	}
}

but my shader seems loaded but I can’t see anything (that I see with the normal ofShader).
Maybe you had same issue.


#8

I do not see any poco lib here

Are you sure you are using the last version of the addon? Anyway, in my case, I am including external library using the ofShader. Something like #pragma include "../../../library/noise.glsl" does not work with ofxAutoReloadShader because, i think, the include needs to be compiled.


#9

:open_mouth:

I think that inadvertently I downloaded the master_0.8.4… don’t know why/how. Sorry!!
Anyway… yes, glslify is very cool! But it’s also good to know how to include some glsl code in a shader in OF.


#10

I just tried to load an external file with ofxAutooReloadedShader and it seems to work.
I tried on fragment. This is my external file inside “myApps/library” folder:

vec3 getColor(){
  return vec3(1.0,0.0,1.0);
}

And this is my fragment inside “data/shaders” folder:

#version 330

#pragma include "../../../library/external.glsl"

out vec4 FragColor;

void main( void ) {
  FragColor = vec4(getColor(),1.0);
}

I’m on High Sierra.