terrain-gen/src/shadowmap.cpp

69 lines
2.2 KiB
C++

#include "shadowmap.h"
QMatrix4x4 ShadowMap::m_bias = QMatrix4x4(0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0);
ShadowMap::ShadowMap(GLsizei size): m_size(size)
{
m_depthProjection.ortho(-100, 100, -100, 100, -100, 100);
}
ShadowMap::~ShadowMap()
{
glDeleteFramebuffers(1, &m_frameBuffer);
glDeleteTextures(1, &m_depthTexture);
}
GLuint ShadowMap::depthTexture() const
{
return m_depthTexture;
}
void ShadowMap::initGl()
{
initializeOpenGLFunctions();
glGenFramebuffers(1, &m_frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
glGenTextures(1, &m_depthTexture);
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_size, m_size, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
glDrawBuffer(GL_NONE);
}
void ShadowMap::preRender()
{
glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, 2048, 2048);
}
void ShadowMap::setUniforms(Shader* program, RenderPassType renderPass)
{
if (renderPass == RenderPassType::SHADOW) {
glUniformMatrix4fv(program->uniformLocation("u_view"), 1, GL_FALSE, m_depthView.data());
glUniformMatrix4fv(program->uniformLocation("u_projection"), 1, GL_FALSE, m_depthProjection.data());
}
QMatrix4x4 depthVP = m_bias * m_depthProjection * m_depthView;
glUniformMatrix4fv(program->uniformLocation("u_depthVP"), 1, GL_FALSE, depthVP.data());
}
void ShadowMap::setLightDirection(QVector3D lightDirection)
{
m_depthView.setToIdentity();
m_depthView.lookAt(lightDirection, QVector3D(0, 0, 0), QVector3D(0, 1, 0));
}