我正在尝试使用 Qt 的 OpenGL 类渲染带有阴影的场景(如下所示平台上的自行车)。
我意识到我们需要为此做两次传球。
第一次从灯光的角度渲染深度图,第二次从相机的角度渲染场景,片段着色器使用深度图作为纹理来确定片段是否在阴影内.
为了捕获深度图,我将从灯光的角度将场景渲染到帧缓冲区中,如下所示
uint ShadowRenderWindow::renderToShadowMap()
{
if(!m_shadowFBO)
{
m_shadowFBO = new QOpenGLFramebufferObject(1024,
1024, QOpenGLFramebufferObject::Depth);
m_shadowFBO->bind();
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
m_shadowFBO->release();
}
m_shadowFBO->bind();
glViewport(0, 0, m_shadowFBO->width(), m_shadowFBO->height());
glEnable(GL_DEPTH_TEST);
glClear(GL_DEPTH_BUFFER_BIT);
m_lightViewMatrix.setToIdentity();
m_lightViewMatrix.lookAt(
m_lightPositionMatrix.map( QVector3D(0,0,0) ),
m_sceneBounds.center(),
m_lightPositionMatrix.map( QVector3D(0,1,0) ).normalized() );
for(int i=0; i<m_models.size()-1; i++)
{
ObjModel *model = m_models.at(i);
model->setRenderMode(ObjModel::ShadowMode);
model->render(m_projectionMatrix, m_lightViewMatrix);
}
m_shadowFBO->release();
return m_shadowFBO->texture();
}
每个模型都使用
m_shader->bind();
model->m_vertexBuffer->bind();
model->m_indexBuffer->bind();
const QMatrix4x4 lightViewProjectionMatrix = projectionMatrix *
lightViewMatrix * model->m_matrix;
m_shader->enableAttributeArray("qt_Vertex");
m_shader->setAttributeBuffer("qt_Vertex", GL_FLOAT, 0, 3, 0);
m_shader->setUniformValue("qt_LightViewProjectionMatrix",
lightViewProjectionMatrix);
Q_FOREACH(ObjModel::Part part, model->m_parts)
{
const uint offset = part.start * sizeof(uint);
glDrawElements(part.type, part.length,
GL_UNSIGNED_INT, (void*)offset);
}
model->m_indexBuffer->release();
model->m_vertexBuffer->release();
m_shader->release();
带顶点着色器
attribute vec3 qt_Vertex;
uniform mat4 qt_LightViewProjectionMatrix;
const float c_one = 1.0;
void main(void)
{
gl_Position = qt_LightViewProjectionMatrix * vec4(qt_Vertex, c_one);
}
和片段着色器
void main(void)
{
gl_FragDepth = gl_FragCoord.z;
}
然后为了在第二遍中使用阴影纹理,我在第二遍的片段着色器中执行此操作。
float evaluateShadow(in vec4 shadowPos)
{
vec3 shadowCoords = shadowPos.xyz / shadowPos.w;
shadowCoords = shadowCoords * 0.5 + 0.5;
float closestDepth = texture2D(qt_ShadowMap, shadowCoords.xy).r;
float currentDepth = shadowPos.z;
float shadow = (currentDepth > closestDepth) ? 1.0 : 0.5;
return shadow;
}
void main(void)
{
vec4 lmColor = evaluateLightMaterialColor(v_Normal);
if(qt_ShadowEnabled == true)
{
float shadow = evaluateShadow(v_ShadowPosition);
gl_FragColor = vec4(lmColor.xyz * shadow, qt_Material.opacity);
}
else
gl_FragColor = lmColor;
}
但以上所有似乎都没有区别。第二遍我看不到任何阴影。
有人可以指出我哪里出错了吗?