title: Incorrect values written in stencil buffer
body: <p>I am trying to pick objects on mouse click. For this I have followed <a href="https://en.wikibooks.org/wiki/OpenGL_Programming/Object_selection#Using_the_stencil_buffer_to_identify_objects" rel="nofollow">this tutorial</a>, and tried to use the stencil buffer for this purpose.</p>
  
  <p>Inside "game" loop I am trying to draw 10 (5 pairs) 'pick'able triangles as follows:</p>
  
  <pre><code>...
  
  glClearColor(red, green, blue, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  
  glClearStencil(0); // this is the default value
  
  /* Enable stencil operations */
  glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  
  /*Some other drawing not involving stencil buffer*/
  
  GLuint index = 1;
  for (GLshort i = 0; i &lt; 5; i++)
  {
      //this returns 2 model matrices
      auto modelMatrices = trianglePairs[i].getModelMatrices(); 
  
      for (GLshort j = 0; j &lt; 2; j++)
      {
          glStencilFunc(GL_ALWAYS, index, -1);
          glUniformMatrix4fv(glGetUniformLocation(ourShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(modelMatrices[j]));
          glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, BUFFER_OFFSET(2));
          index++;
      }
      /*Some other drawing not involving stencil buffer*/
  }
  
  /*Some other drawing not involving stencil buffer*/
  ...
  </code></pre>
  
  <p>However, when I am trying to read back the stencil values, I am getting wrong values. I am reading back the values as (this is also a <a href="https://en.wikibooks.org/wiki/OpenGL_Programming/Object_selection#Reading_back_information_from_the_framebuffer" rel="nofollow">part of the above-mentioned tutorial</a>):</p>
  
  <pre><code>GLuint index;
  glReadPixels(xpos, Height - ypos - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &amp;index);
  </code></pre>
  
  <p>Whenever, I click the first triangle of the pair I am getting values as <code>i+1</code>, whereas the correct value should have been <code>i</code>, and for the second triangle of the pair, I am getting <code>0</code> as <code>index</code>. </p>
  
  <p>Please let me know what am I missing here?</p>
  
  <p><strong>Update</strong>
  I have found that stencil values can be applied on quads. When I tried to apply the stencil value on unit square it worked correctly. However, when the quad is not unit square, it returns <code>0</code>. What is the reason for this?</p>