# How can I write only to the stencil buffer in OpenGL ES 2.0?

I'd like to write to the stencil buffer without incurring the cost of my expensive shaders. As I understand it, I write to the stencil buffer as a 'side effect' of rendering something. In this first pass where I write to the stencil buffer, I don't want to write anything to the color or depth buffer, and I definitely don't want to run through my lighting equations in my shaders.

Do I need to create no-op shaders for this (and can I just discard fragments), or is there a better way to do this?

As the title says, I'm using OpenGL ES 2.0.

I haven't used the stencil buffer before, so if I seem to be misunderstanding something, feel free to be verbose.

## 1 Answer

Disable writing to the color buffer and depth buffer:

glColorMask(false, false, false, false);
glDepthMask(false);


Then do your draw as normal (with stencil testing/writing enabled), and restore color/depth writing afterward by repeating those calls with true instead of false. This should automatically short-circuit the pixel shader, I believe.

• I saw this in an example I was following. The documentation for glColorMask() doesn't specify whether this would result in the pixel shader being bypassed or not. I guess I could test this fairly easily, but I'm afraid it would vary from implementation to implementation anyway. – notlesh Nov 17 '11 at 22:34
• I'd play safe and write a no-op fragment shader (and a vertex shader that just transforms but does nothing else). Never trust the drivers... :) I suspect using discard would not write to stencil either though, so it would be better to set the fragment color to 1, 1, 1, 1 instead. – Maximus Minimus Nov 17 '11 at 22:37
• I'll have to play with it, I guess, but in this particular case it's important that I not write anything to the color buffer. Maybe I can write vec4(0.0, 0.0, 0.0, 0.00001) if discard doesn't work or is unreliable. – notlesh Nov 18 '11 at 5:11
• You can combine a one-instruction pixel shader with the glColorMask call above, to ensure that nothing is written and the pixel shader also isn't doing wasted work. – Nathan Reed Nov 18 '11 at 6:03
• @stephelton using glColorMask is enough to get sure that nothing is written to the color buffer. No need to output some artificially small color or such rubbish. Just make sure the fragment shader doesn't do unneccessary work and write out a vec4(1.0). – Christian Rau Nov 18 '11 at 12:35