Android OpenGL ES 1.1: Read from Stencil Buffer

1.1k views Asked by At

Using Android OpenGL ES 1.1 (HTC Desire)...

The problem I have in general is this:

I have various 3D objects rendered in a complex scene. I want to check if the user has clicked on a particular object. This object may be partially hidden and therefore may appear as almost any shape in the scene. I only want to allow the object to be "selected" if the user clicks on a part of the object that is visible in the scene. This means that I cannot use vector-based calculations for the object intersection since these could not easily take into account the hidden areas of the object.

So I came up with an idea...

I set up the stencil buffer such that wherever the object was visible the stencil buffer was filled with 1s and everywhere else in the stencil buffer is 0. When the user clicks on a particular pixel in the scene I just need to check the stencil buffer to see if it contains a 1 or 0 which indicates if the object was clicked or not.

This works perfectly on a PC, but on Android OpenGL ES 1.1 it seems that I cannot read from the stencil buffer by using glReadPixels() as GL_STENCIL_INDEX is not supported.

Does anyone know if there is a way to read this 0/1 from the stencil buffer? Or can anyone think of a better algorithm for determining if my object has been clicked?

Many thanks

1

There are 1 answers

1
Jayesh On

You can implement the same algorithm using color buffer.

Create a FrameBuffer. Render the scene into it, but draw each object with a distinct color. The color doesn't have to be same as the actual color of the object, because what you draw in framebuffer is not for eyes, but only for mouse lookup. Once entire scene is drawn, read the pixels using glReadPixels. When you get coordinates of the mouse from mouse event, look them up in the pixel map. The color you find can point back to the object the mouse is currently on.

It may be more efficient to use stencil buffer, but reading stencil buffer into memory doesn't seem possible in OpenGL ES. On the other hand, this method's advantage is you are not limited to 255 objects as in case of 8-bit stencil buffer.