title: OpenGL ES stencil operations
body: <p>In reference to the problem diskussed in article <a href="https://stackoverflow.com/questions/7538270/opengl-clipping">OpenGL clipping</a> a new question arises.</p>
  
  <p>I am implementing the clipping for a node based 2D scene graph. Whenever the clipping boxes are axis aligned I am using the glScissor like proposed in  <a href="https://stackoverflow.com/questions/7538270/opengl-clipping">OpenGL clipping</a>. I have sucessfully implemented node clipping of boxes that are axis aligned. </p>
  
  <p>It turns out that each node has to intersect it's clipping rectangle with the ones of it's ancestors that use clipping. (That is necessary in case of siblings that are overlapping with the clipping box of an ancestor). </p>
  
  <p>The mechanism of intersecting non axis aligned rectangles has to be implemented using the stencil buffer. I started implementing the proposed solution in <a href="https://stackoverflow.com/questions/7538270/opengl-clipping">OpenGL clipping</a> but am having problems with chidrens having clip rects overlaping with theyr ancestors ones.</p>
  
  <p>Right now stencil clipping works perfect with only one clipping box. 
  But in case of a child or grand child that intersects with an ancestor the algorith fails, because the intersection of the 2 involved rectangles would be needed here (like in the axis aligned version) as mask and not the full rectangle of the child.</p>
  
  <p>I have thought out the following algorithm:</p>
  
  <p>The topmost node writes starts with a counter value of 1 and draws it's clipping rectangle filled with 1s into the stencil buffer and renders it's children stencil-testing against 1. Each sibling that also has clipping turned on draws it's bounding rectangle by <strong>adding</strong> 1 to the stencil buffer and then testing against 2 and so on. Now when a siblings clipping rect overlaps with an ancestors   one,the region where they overlap will be filled with 2s, giving perfect clipping when testing against 2. This algorithm can be extended to a maximum of 255 nested clipping nodes.</p>
  
  <p>Here comes my questions:</p>
  
  <p>How do I perform rendering to the stencil buffer in a way that instead of 1s being writing,1s are added to the current stencil buffer value, whenever rendering is performed. </p>
  
  <p>This is my code I use to prepare for rendering to the stencil buffer:</p>
  
  <pre><code>glEnable(GL_STENCIL_TEST);
  glStencilFunc(GL_ALWAYS, ref, mask);
  glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  </code></pre>
  
  <p>I am looking for a setup that will increase the stencil buffers current value by the value of ref instead of writing ref into the buffer.</p>
  
  <p>Can someone help me out?</p>