PDA

View Full Version : Variable number of clip planes and gl_ClipDistance



OctoOcto
11-29-2016, 10:56 AM
Hi,

What would be the best way to handle a variable number of clip planes in a GLSL shader?
I work on an application in which a user can add 0 to N clipping planes in a scene.
N being the max allowed.

It seems that with gl_ClipDistance, I have to declare gl_ClipDistance[N] and compute the distance N times.
Even if no clipping plane is enabled.

Is there a way to compute gl_ClipDistance no more than the actual number of clip planes enabled?

Thank you.

Octo

GClements
11-29-2016, 01:35 PM
What would be the best way to handle a variable number of clip planes in a GLSL shader?
I work on an application in which a user can add 0 to N clipping planes in a scene.
N being the max allowed.

It seems that with gl_ClipDistance, I have to declare gl_ClipDistance[N] and compute the distance N times.
Even if no clipping plane is enabled.

The size needs to be enough to cover all enabled clip planes. The elements corresponding to enabled clip planes need to be assigned to. Elements corresponding to non-enabled planes don't need to be assigned to.



Is there a way to compute gl_ClipDistance no more than the actual number of clip planes enabled?

Pass the number of enabled planes (or a bit mask of enabled planes) via a uniform variable.

In this situation, the array will need to be redeclared with an explicit size. By default, it is implicitly declared unsized, so can only be indexed with integer constant expressions.

If you're concerned about using more output components than are necessary, you could re-compile the shader whenever the number of enabled planes changes.

OctoOcto
11-30-2016, 11:58 AM
I try to pass the number of planes but iterating over a uniform does not seem to work.
I only get clipping if the for loop has a constant number of iterations.



#version 150

const int MAX_CLIP_PLANES = 8; // THIS MUST MATCH THE MAX SET IN THE C++ CODE

uniform vec4 clip_planes[MAX_CLIP_PLANES];
uniform int nb_clip_planes; // must not exceed MAX_CLIP_PLANES

void computeClipDistance(vec3 pos)
{
for(int i = 0; i < nb_clip_planes; i++ )
{
gl_ClipDistance[i] = dot( clip_planes[i], vec4(pos, 1.0) );
}
}

GClements
11-30-2016, 01:17 PM
I only get clipping if the for loop has a constant number of iterations.

Did you remember to re-declare gl_ClipDistance[] with an explicit size? I don't see it in the posted code.

OctoOcto
11-30-2016, 01:37 PM
Indeed I had forgotten. Yet after adding redeclaration, it still fails to clip.



#version 150

const int MAX_CLIP_PLANES = 1; // THIS MUST MATCH THE MAX SET IN THE C++ CODE

float gl_ClipDistance[MAX_CLIP_PLANES];

uniform vec4 clip_planes[MAX_CLIP_PLANES];
uniform int nb_clip_planes; // must not exceed MAX_CLIP_PLANES

void computeClipDistance(vec3 pos)
{
for(int i = 0; i < nb_clip_planes; i++ )
{
gl_ClipDistance[i] = dot( clip_planes[i], vec4(pos, 1.0) );
}
}