【发布时间】:2022-01-19 15:38:07
【问题描述】:
我有两个来自同一个光源的同一个物体的平面阴影——一个投射在地板上,一个投射到墙上,当物体足够近时。就投射的阴影而言,一切正常,我使用模板缓冲区来确保两个阴影仅投射在各自的表面上,而不会渲染到房间外。
问题是两个模板缓冲区相互渗入,特别是我渲染第二个阴影的任何阴影渗入第一个模板缓冲区。我认为这是模板功能或其他东西的问题,使用了错误的参数,但我似乎无法弄清楚。
// Generate the shadow using a shadow matrix (created using light position and vertices of
// the quad on which the shadow will be projected) and the object I'm making a shadow of
void createShadow(float shadowMat[16])
{
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
// Set the shadow color
glColor3f(0.1, 0.1, 0.1);
glPushMatrix();
// Create the shadow using the matrix and the object casting a shadow
glMultMatrixf((GLfloat*)shadowMat);
translate, rotate etc;
render object;
glPopMatrix();
// Reset values to render the rest of the scene
glColor3f(1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
}
// Set up the stencil buffer and render the shadow to it
void renderShadow(float shadowMat[16], float shadowQuad[12])
{
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glDisable(GL_DEPTH_TEST);
// Create a stencil for the shadow, using the vertices of the plane on which it will
// be projected
glPushMatrix();
translate, rotate etc;
glEnableClientState(GL_VERTEX_ARRAY);
// The shadow quad is the same vertices that I use to make the shadow matrix
glVertexPointer(3, GL_FLOAT, 0, shadowQuad);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
glEnable(GL_DEPTH_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// Render the shadow to the plane
createShadow(shadowMat);
glDisable(GL_STENCIL_TEST);
}
// In the render function:
Render floor/surrounding area;
Set up light using the same position used to make the shadow matrix;
renderShadow(wallShadowMatrix, wallVertices);
renderShadow(floorShadowMatrix, floorVertices);
Render rest of scene;
如果我自己渲染阴影,它们会按预期工作,但是当我将它们一起渲染时,无论哪个渲染的第二个都会出现在第一个阴影的模板中。
我已经包含了一些图片;前两个显示个人Shadow on the wall 和Shadow on the floor,这里是floor shadow rendered after the wall shadow 和vice versa。
【问题讨论】:
标签: c++ opengl shadow stencil-buffer