Haplue
Haplue

Reputation: 70

OpenGL Enable Clip Distance

I'm trying to render a proper refraction/reflection in my OpenGL project and I need to use clip distance. I'm following the tutorial by Thin Matrix.

I enable the clip distance with

glEnable(GL_CLIP_DISTANCE0);

in my game loop and then I try to use it in the vertex shader like this

gl_ClipDistance[0] = -1;

I've tried to change around the -1 value but nothing happens no matter what I do. Is there something more I need to do to enable it properly?

Upvotes: 2

Views: 2431

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473292

The gl_ClipDistance array contains a series of floating-point values that represent, for each vertex, which side of a conceptual "plane" it is on. Each array index is a conceptual "plane". The vertex can be either on the negative side, or the non-negative side.

If two vertices of the same line/triangle are on two difference sides of the plane (that is, one vertex has a negative value and the other a non-negative one), then the primitive will be clipped at the location where that distance is 0. The part of the primitive on the non-negative side will be visible.

Given that, what you need to do is set up a clip distance value that represents the distance between the vertex position and the plane you want to clip against. The standard plane equation (Ax + By + Cz + D = 0) gives us a way to handle this. The distance of a point from the plane A, B, C, D, assuming the vector (A, B, C) is a unit vector, is simply:

dot(point, vec3(A, B, C)) + D

This also assumes that point is in the same space as A, B, C and D.

Of course, if point is a vec4, with the last component as 1.0, then you can just do this:

dot(point, plane);

Where plane is a vec4 that contains A, B, C, and D. And that's your clip distance.

You also need to redeclare gl_ClipDistance with an explicit size in the shader stage that uses it. In GLSL 3.20+, gl_ClipDistance lives inside an interface block, so you have to redeclare that:

out gl_PerVertex
{
  vec4 gl_Position;
  float gl_ClipDistance[1];
};

Upvotes: 6

Related Questions