How to read back stencil buffer

Hi all,

I’m need read back the stencil buffer, see the below code

// Disable depth buffer updates. Pass pixels if nearer than stored depth value
// Increment stencil buffer for object A frontfaces
// Decrement stencil buffer for object A backfaces
// Read back stencil buffer. 

I need it for determining if two objects are colliding or not.



Read back as in copy to system memory? You can use glReadPixels() for that. It’ll most likely be awfully slow though.

exactly, using glReadPixels. But what params should i use? I’m not sure of using GL_STENCIL_INDEX, anybody have an illustrative example?

This should do:

glDrawPixels(width, height, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, data);

@ Humus: why would it be awfully slow ? I haven’t done it yet. But, from my point of view, it should be faster than doing for example real-time shadow mapping or anything involving read/write/copy from textures and FBOs : the stencil buffer is only 8 bits sized. Has it something to do with non-hardware support ?

Thanks Humus,
I would like to know if nowadays exist someway of render to Stencil Buffer and attach it as a texture, for instance, using EXT_packed_depth_stencil.

Originally posted by jide:
@ Humus: why would it be awfully slow ?
glReadPixels() is always slow because it forces a glFinish() and thus kills all parallelism, and it copies the data to system memory, which is slow. So even when it’s accelerated, things are quite slow. With stencil readback I don’t think it’ll be accelerated either.

Thanks Humus.

yalmar, you can use FBO to deal with render to stencil, using stencil render buffer objects. But AFAIK, you can’t directly attach it to a texture. I guess you’ll have to deal with read/write pixels on a 8 bits monochromatic texture.

what a pity,


Are you sure you really need to read back stencil though? Can’t you use an occlusion query to solve the problem?

Originally posted by jide:
I would like to know if nowadays exist someway of render to Stencil Buffer and attach it as a texture, for instance, using EXT_packed_depth_stencil.
Yes. EXT_packed_depth_stencil enables you to render your stencil content to an FBO that has a DEPTH_STENCIL attachment. The depth_stencil format is supported for both texture and renderbuffer objects.

Also, if you must do ReadPixels of stencil data, you are best off using ReadPixels of DEPTH_STENCIL data format and UNSIGNED_INT_24_8 packed data type. This ReadPixels usage was first supported long ago by the NV_packed_depth_stencil upon which EXT_packed_depth_stencil is based.

JeffJ, I haven’t wrote that quote ! :slight_smile:

Oops, sorry, yalmar wrote the text I quoted. I had a copy/paste typo that I failed to notice when previewing.

Thanks for your replies. I will attempt to use that extension (EXT_packed_depth_stencil).