OpenGL Stenciling, separating ref from value writt

2019-08-06 19:58发布

问题:

The following code sets up the stencil test to see if ref is greater than the stored value in the stencil buffer, and if it is, it'll write ref to the stencil buffer

unsigned int ref = 42;
glStencilFunc(GL_GREATER, ref, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

The problem is that while I do want to test the stencil buffer against ref, I don't want to write ref to it if it succeeds, I want to write a totally different value. The only option I've found is GL_INCR which can take the place of GL_REPLACE, but that's not very useful if the stencil buffer has a lot of stuff already written to it that can't be cleared out beforehand.

Is there a way to... say, test to see if 42 is greater than what's stored in the stencil buffer, and if it is, write 100 or something else to it?

回答1:

I don't believe this functionality is available in standard OpenGL. The closest I found is a vendor specific extension: AMD_stencil_operation_extended.

This supports exactly what you're looking for:

Additionally, this extension separates the value used as the source for stencil operations from the reference value, allowing different values to be used in the stencil test, and in the update of the stencil buffer.

Just from reading the spec, the calls should look something like this, with val the stencil value you want to set:

glStencilFunc(GL_GREATER, ref, 0xFF);
glStencilOpValueAMD(GL_FRONT_AND_BACK, val);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE_VALUE_AMD);