Question

I've been trying for so long now to find how to do this: Clipping outside a defined area in OpenGL.

I don't want to clip using the viewport or scissors btw. I've been searching like crazy and all I ever find is how to use the viewport/scissors.

I want to define something like, "if this pixel has x below 10 units don't draw it". Something like, "it's ok to draw if x is between 10-20 and y is between 10-20 and z is between 10-20, otherwise don't render the pixel".

Footnote: Sucks that stackoverflow requires you to register to ask a question. It was better before when the site was open and account creation was optional.

Was it helpful?

Solution

Figured it out after searching a little while longer, typical that I just made the question on this site.

Java code (I'm using LWJGL):

DoubleBuffer eqn1 = BufferUtils.createDoubleBuffer(8).put(new double[] {-1, 0, 0, 100});
eqn1.flip();
GL11.glClipPlane(GL11.GL_CLIP_PLANE0, eqn1);
GL11.glEnable(GL11.GL_CLIP_PLANE0);

As usual OpenGL is badly (as in poorly, not easy to grasp) documented and I had to search around until finally I found some that explained this on some forum (and revealed that the buffer must be flipped): The first three doubles are the normal of the clipping plane, the last (100) is how far from world's origin (0,0,0) the plane is.

So, if the camera is looking straight at (0,0,0) this example code above will create a plane on the right side that makes OpenGL not render stuff to the right of it. The plane is located on x=100 and is facing to the left (-1).

I hope this will be the search result for people looking for the answer to this in the future.

OTHER TIPS

The Fixed-Function has user-defined clipping planes for that, see glClipPlane() for the details. You could define 6 of these planes to achieve the effect you talked about.

Modern shader-based GL provides the gl_ClipDistance[] output variable array to implement such things.

The test you describe seems to be per-fragment, so you could also do this in the fragment shader, by discarding all fragments outside of your area. But this will be quite inefficient (and prevents the early Z test to be used), so you should be careful. This could probably combined with the stencil test to limit x and y and only do the test on z in the shader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top