How to get StencilBuffer into a texture?

I need to get the silhouette of a mesh into a texture. Can I use a stencil buffer for this?

I’ve used a WebGLRenderTarget to extract the depth texture from my scene in the past, and I was wondering if the same was possible with the stencil buffer? The docs state that there is a .stencil boolean to set to true, but then how do I use this stencil data? Wikipedia says that the stencil buffer should have 1 byte per pixel, so is there a way to extract this black-and-white texture to use in my shaders?

I found this similar question from 3 years ago, but there was no resolution.

You can use the stencil but I given your use case I wouldn’t recommend it. The stencil buffer is intended to be written to, incremented, or decremented during draw calls and then subsequently used to mask pixels to write to in future draw calls. And as far as I know there’s no simple way to copy all 8 stencil bits to a color buffer but by drawing a full screen quad with stencil testing enabled you could see all pixels which match your settings.

If you just want the black and white silhouette of a mesh, though, I’d clear the render target with the color black and then draw the mesh using a white MeshBasicMaterial.

1 Like

Can you achieve your effect by using the same depth/stencil buffer on your render target?

For future reference, here’s a demo using stencil testing to perform something similar. The only caveat is that it’s using Three r73, so it might need some updates for modern versions: