Stencil buffer behaviour in simple case (GL_ALWAYS, GL_LEQUAL)

158 views Asked by At

I don't understand why those two codes doesn't yield the same result. I have enabled depth testing and stencil testing and my main loop looks like this :

myShader.Use() // Use shader program
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// define model, projection, view, ....
glBindVertexArray(VAO[0]);
glStencilMask(0xFF); // Enable stencil buffer writing
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
drawCube(&myShader, model, projection, view);
glBindVertexArray(0);

Obviously, my cube renders in this case.

However, if I use this code, nothing renders at all :

myShader.Use() // Use shader program
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// define model, projection, view, ....
glBindVertexArray(VAO[0]);
glStencilMask(0xFF); // Enable stencil buffer writing
glStencilFunc(GL_LEQUAL, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
drawCube(&myShader, model, projection, view);
glBindVertexArray(0);

With only one object in my scene, both code should behave the same way. Yet, it doesn't.

I thought it had something to do with the default value in the stencil buffer. However, since I'm clearing the stencil buffer before doing this, the default value should be 0.

By the way, with this code, the cube renders as well :

myShader.Use() // Use shader program
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// define model, projection, view, ....
glBindVertexArray(VAO[0]);
glStencilMask(0xFF); // Enable stencil buffer writing
glStencilFunc(GL_LEQUAL, 0, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
drawCube(&myShader, model, projection, view);
glBindVertexArray(0);

I don't understand what is happening.

1

There are 1 answers

0
Rabbid76 On BEST ANSWER

glStencilFunc(GL_LEQUAL, 1, 0xFF) means if 1 <= 0, because the stencil buffer contains 0, since you cleared it. The reference value is 1, because you pass this value to the function. This always fails.

See the Khronos reference page (glStencilFunc):

GL_LEQUAL Passes if ( ref & mask ) <= ( stencil & mask ).