Enabling the stencil buffer in JOGL (OpenGL & Java)
In OpenGL the stencil buffer is used to mask pixels on the screen. This can be used for shadow volume rendering, as well as a myriad of other applications. Constructing stencil tests is the same as in C, for example glStencilFunc(GL_KEEP,GL_KEEP, GL_INCR); is just as valid in Java. However, if you’re noticing that your stencil test is always passing, i.e. your stencil bits are always returned as 0, then you probably haven’t initialized the stencil bits.
In order to use stencil tests, you MUST (emphasize MUST) request stencil bits to the canvas. Otherwise, the test will always pass. This isn’t incredibly well documented for JOGL… It took a few days of internet searching until I found a breadcrumb of help on this. In C, one would be using GLUT, so calling glutInitDisplayMode() would be the function to call to request stencil bits. In Java, this is in the GLCapabilities object.
So, to request stencil bits, in your init() function, put:
GLCapabilities cap = new GLCapabilities(); cap.setStencilBits(8); GLCanvas canvas = new GLCanvas(cap);
or incorporate this into your code wherever deems fit. Basically this says, initialize new GLCapabilities, and assign 8 bits in the stencil buffer. Then when you create your GLCanvas, set it as a parameter. Now you’re good to go, and your stencil tests should work!





Thank you. Saved me a lot of frustration. :-)
Luckily this website came up as one of the first when searching for this problem.
thx, saved me a lot of time.