Sign in to follow this  
mychii

Shaders (GLSL) in one file? Is it practical?

Recommended Posts

Hi, I'm currently playing around with WebGL, which of course, like OpenGL, deal with shaders. Since web always download files, I started to think that I better combine both vertex and fragment shaders into one file so I can just request that file as one shader program entirely.

 

Do you think it's practical? Is there any possibility that either shader importantly/needed to be shared among each other?

 

Thanks.

Share this post


Link to post
Share on other sites

It's very convenient. For example:

#define FRAGMENT_PROGRAM

#define VERTEX_PROGRAM

#version 330

 

#ifdef VERTEX_PROGRAM

 

layout(location = 0) in vec4 in_vertex;

...

 

#endif

#ifdef FRAGMENT_PROGRAM

 

...

 

#endif

 

That makes loading the file relatively simple, since you just run it through a function that spits out both vertex and fragment:

One string without the first define, and the second without the other. The rest of the files contents are still present in both files, but the shader compiler will compile only the relevant parts. Take care though if you are compiling shaders during rendering. In that case you will want to pay special attention to the length of the shader code.

 

The benefit of doing this, is reducing the number of files you need to keep track of, and in the webserver case, the files you need to transfer

The contents in both are related in that the vertex program sends data to the fragment program. The transferred data you use in the fragment shader must come from matching out statements on the vertex program.

 

I used to separate the files previously, and it was OK. I just got to the point where I had alot of shaders, and it helped abit to reduce number of files.

You do lose the ability to combine common vertex programs with specialized shaders, such as the generic fullscreen quad vertex shader.

Edited by Kaptein

Share this post


Link to post
Share on other sites

As Kaptein suggested, as you load the file into your program, you just prepend the correct ifdef before the shader source code before sending it to OpenGL.

Another way of doing this could be as follows.

char *sources[2] = { "#version 330\n#define VERTEX_PROGRAM\n", sourceFromFile };
glShaderSourceARB(shader, 2, sources, NULL);

This basically send the define to OpenGL just before the rest of the shader source.

Edited by Karsten_

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this