在模板缓冲区中写入的值不正确

时间:2016-06-22 05:29:22

标签: c++ opengl stencil-buffer picking

我试图在鼠标点击时选择对象。为此我遵循this tutorial,并尝试使用模板缓冲区来实现此目的。

内部"游戏"循环我试图绘制10(5对)'挑选三角形如下:

...

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 < 5; i++)
{
    //this returns 2 model matrices
    auto modelMatrices = trianglePairs[i].getModelMatrices(); 

    for (GLshort j = 0; j < 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*/
...

然而,当我试图回读模板值时,我得到了错误的值。我正在读取值(这也是part of the above-mentioned tutorial):

GLuint index;
glReadPixels(xpos, Height - ypos - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

每当我点击该对中的第一个三角形时,我得到的值为i+1,而正确的值应该是i,对于该对的第二个三角形,我得到{ {1}} 0

请让我知道我在这里失踪了什么?

更新 我发现模板值可以应用于四边形。当我试图在单位正方形上应用模板值时,它正常工作。但是,当四边形不是单位平方时,它返回index。这是什么原因?

0 个答案:

没有答案