The idea is to take a beach ball that is hovering over a floor and put a reflection of the ball on the floor using the stencil buffer. How it’s implemented is like this:
Pass #1
- the color mask is set to 0 so that nothing will be seen
- tell opengl that the stencil test will always pass; reference and destination values are 1
- when the test passes, 1s are put into the stencil buffer where the floor would be drawn
- the floor is drawn (but not visible)
Pass #2
- the color mask is set to all 1s this time
- set the stencil test to GL_EQUAL; reference and destination values are still 1
- clip the plane (0, -1, 0) (the floor is in the middle of the screen)
- reflect the ball upside down glScale3f(1, -1, 1)
- the ball is drawn (this will be the reflection)
Pass #3
- stencil testing is not used this time
- the floor is drawn (with blending) on top of the ball that was drawn before
Pass #4
- the real ball that hovers is drawn
The problem is that the reflection is clipped when it comes “up”, but when the reflection goes down (as the real ball goes higher) the reflection pops out of the floor, which is what the stencil buffer is supposed to stop. Hopefully this image works:
You can also view the code (only the part that I’m having problems with)