Pro OpenGL ES for iOS

(singke) #1

220 CHAPTER 7: Well-Rendered Miscellany^


Essentially, you render something to the stencil buffer as you would to any other, but in
this case, any pixel and its value are used to determine how to render future images to
the screen. The most common case is that any later image drawn to the stencil area will
be rendered as it normally would, whereas anything outside of the stencil area is not
rendered. These behaviors can be modified, of course, keeping with OpenGL’s
philosophy of making everything more flexible than the vast majority of engineers would
use, let alone understand. Still, it can be very handy at times. We’ll stay with the simple
function for the time being.
Listing 7-8. The stencil is generated like a normal screen object

-(void)renderToStencil
{
glEnable(GL_STENCIL_TEST); //1
glStencilFunc(GL_ALWAYS,1, 0xffffffff); //2

glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); //3

[self renderStage]; //4

glStencilFunc(GL_EQUAL, 1, 0xffffffff); //5
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); //6
}
So, you establish your stencil the following way:
„ Enable the stencil as done in line 1.
„ Here in line 2 we specify the comparison function used whenever
something is writing to the stencil buffer. Since we clear it each time
through, it will be all zeros. The function GL_ALWAYS says that every
write will pass the stencil test, which is what we want when
constructing the stencil. The value of 1 is called the reference value.
Since you can have any value from 0 to 255, it is possible to have a
stencil behave differently based on the reference value supplied and
how the stencil-op is set. The final value is a mask for the bit planes to
access. Since we’re not concerned about it, let’s just turn them all on.
„ Line 3 specifies what to do when a stencil test succeeds or fails. The
first parameter pertains if the stencil test fails; the second, if the stencil
passes but the depth test fails; and the third, if both succeed. Since
we are living in 3D space here, having the stencil tests coupled to
depth testing recognizes that there may be situations in which one
overrules the other. Some of the subtleties in the use of the stencil
buffer can get quite complicated. In this case, set all three to
GL_REPLACE. Table 7-1 shows all the other permissible values.
Free download pdf