Commit ebeae5dc authored by Laszlo Agocs's avatar Laszlo Agocs
Browse files

shadowmap example skeleton

Shaders and camera logic not yet there.

It is essential to have a test that exercises depth-only passes and
rendering into a depth texture that is then used in another pass. Some
simple shadow casting directional light is a good example for this.
parent fbeefcd7
......@@ -14,7 +14,8 @@ SUBDIRS += \
triquadcube \
offscreen \
floattexture \
mrt
mrt \
shadowmap
qtConfig(vulkan) {
SUBDIRS += \
......
qsb --glsl 120 --hlsl 50 --msl 12 -c shadowmap.vert -o shadowmap.vert.qsb
qsb --glsl 120 --hlsl 50 --msl 12 -c shadowmap.frag -o shadowmap.frag.qsb
qsb --glsl 120 --hlsl 50 --msl 12 -c light.vert -o light.vert.qsb
qsb --glsl 120 --hlsl 50 --msl 12 -c light.frag -o light.frag.qsb
#version 440
layout(location = 0) in vec3 vECVertNormal;
layout(location = 1) in vec3 vECVertPos;
layout(location = 0) out vec4 fragColor;
void main()
{
vec3 ECCameraPosition = vec3(0.0, 0.0, 4.0); // matches C++
vec3 ka = vec3(0.05, 0.05, 0.05);
vec3 kd = vec3(0.3, 0.7, 0.6);
vec3 ks = vec3(0.66, 0.66, 0.66);
vec3 ECLightPosition = vec3(0.0, 10.0, 1.0); // matches C++
vec3 attenuation = vec3(1.0, 0.0, 0.0);
vec3 color = vec3(1.0, 1.0, 1.0);
float intensity = 0.8;
float specularExp = 150.0;
vec3 unnormL = ECLightPosition - vECVertPos;
float dist = length(unnormL);
float att = 1.0 / (attenuation.x + attenuation.y * dist + attenuation.z * dist * dist);
vec3 N = normalize(vECVertNormal);
vec3 L = normalize(unnormL);
float NL = max(0.0, dot(N, L));
vec3 dColor = att * intensity * color * NL;
vec3 R = reflect(-L, N);
vec3 V = normalize(ECCameraPosition - vECVertPos);
float RV = max(0.0, dot(R, V));
vec3 sColor = att * intensity * color * pow(RV, specularExp);
fragColor = vec4(ka + kd * dColor + ks * sColor, 1.0);
}
#version 440
layout(location = 0) in vec4 position;
layout(location = 1) in vec3 normal;
layout(std140, binding = 0) uniform buf {
mat4 mvp;
mat4 mv;
mat4 m;
mat3 n;
} ubuf;
out gl_PerVertex { vec4 gl_Position; };
layout(location = 0) out vec3 vECVertNormal;
layout(location = 1) out vec3 vECVertPos;
void main()
{
vECVertNormal = normalize(ubuf.n * normal);
vECVertPos = vec3(ubuf.m * position);
gl_Position = ubuf.mvp * position;
}
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../shared/examplefw.h"
#include "../shared/cube_with_normals.h"
// Depth texture / shadow sampler / shadow map example.
// Not available on GLES 2.0.
static float quadVertexData[] =
{ // Y up, CCW, x-y-z, normalX-normalY-normalZ
-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
static quint16 quadIndexData[] =
{
0, 1, 2, 0, 2, 3
};
struct {
QVector<QRhiResource *> releasePool;
QRhiBuffer *vbuf = nullptr;
QRhiBuffer *ibuf = nullptr;
QRhiBuffer *ubuf = nullptr;
QRhiShaderResourceBindings *srb = nullptr;
QRhiGraphicsPipeline *ps = nullptr;
QRhiResourceUpdateBatch *initialUpdates = nullptr;
QMatrix4x4 winProj;
float cubeRot = 0;
QRhiTextureRenderTarget *rt = nullptr;
QRhiRenderPassDescriptor *rtRp = nullptr;
QRhiTexture *shadowMap = nullptr;
QRhiGraphicsPipeline *shadowPs = nullptr;
} d;
const int UBLOCK_SIZE = 64 + 64 + 64 + 48;
const int UBUF_SLOTS = 4; // 2 objects * 2 passes with different cameras
void Window::customInit()
{
if (!m_r->isTextureFormatSupported(QRhiTexture::D32F))
qFatal("Depth texture is not supported");
d.vbuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(quadVertexData) + sizeof(cube));
d.vbuf->build();
d.releasePool << d.vbuf;
d.ibuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::IndexBuffer, sizeof(quadIndexData));
d.ibuf->build();
d.releasePool << d.ibuf;
const int oneRoundedUniformBlockSize = m_r->ubufAligned(UBLOCK_SIZE);
d.ubuf = m_r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SLOTS * oneRoundedUniformBlockSize);
d.ubuf->build();
d.releasePool << d.ubuf;
d.srb = m_r->newShaderResourceBindings();
d.releasePool << d.srb;
const QRhiShaderResourceBinding::StageFlags stages = QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
d.srb->setBindings({ QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, stages, d.ubuf, 64) });
d.srb->build();
d.ps = m_r->newGraphicsPipeline();
d.releasePool << d.ps;
d.ps->setShaderStages({
{ QRhiGraphicsShaderStage::Vertex, getShader(QLatin1String(":/light.vert.qsb")) },
{ QRhiGraphicsShaderStage::Fragment, getShader(QLatin1String(":/light.frag.qsb")) }
});
d.ps->setDepthTest(true);
d.ps->setDepthWrite(true);
// fits both the quad and cube vertex data
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({
{ 6 * sizeof(float) }
});
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float3, 0 },
{ 0, 1, QRhiVertexInputAttribute::Float3, 3 * sizeof(float) }
});
d.ps->setVertexInputLayout(inputLayout);
d.ps->setShaderResourceBindings(d.srb);
d.ps->setRenderPassDescriptor(m_rp);
d.ps->build();
d.initialUpdates = m_r->nextResourceUpdateBatch();
d.initialUpdates->uploadStaticBuffer(d.vbuf, 0, sizeof(quadVertexData), quadVertexData);
d.initialUpdates->uploadStaticBuffer(d.vbuf, sizeof(quadVertexData), sizeof(cube), cube);
d.initialUpdates->uploadStaticBuffer(d.ibuf, quadIndexData);
d.shadowMap = m_r->newTexture(QRhiTexture::D32F, QSize(512, 512), 1, QRhiTexture::RenderTarget);
d.releasePool << d.shadowMap;
d.shadowMap->build();
QRhiTextureRenderTargetDescription rtDesc;
rtDesc.setDepthTexture(d.shadowMap);
d.rt = m_r->newTextureRenderTarget(rtDesc);
d.releasePool << d.rt;
d.rtRp = d.rt->newCompatibleRenderPassDescriptor();
d.releasePool << d.rtRp;
d.rt->setRenderPassDescriptor(d.rtRp);
d.rt->build();
d.shadowPs = m_r->newGraphicsPipeline();
d.releasePool << d.shadowPs;
d.shadowPs->setShaderStages({
{ QRhiGraphicsShaderStage::Vertex, getShader(QLatin1String(":/shadowmap.vert.qsb")) },
{ QRhiGraphicsShaderStage::Fragment, getShader(QLatin1String(":/shadowmap.frag.qsb")) }
});
d.shadowPs->setDepthTest(true);
d.shadowPs->setDepthWrite(true);
inputLayout.setBindings({
{ 6 * sizeof(float) }
});
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float3, 0 }
});
d.shadowPs->setVertexInputLayout(inputLayout);
d.shadowPs->setShaderResourceBindings(d.srb);
d.shadowPs->setRenderPassDescriptor(d.rtRp);
d.shadowPs->build();
}
void Window::customRelease()
{
for (QRhiResource *r : d.releasePool)
r->releaseAndDestroy();
d.releasePool.clear();
}
static void enqueueScene(QRhiCommandBuffer *cb, int oneRoundedUniformBlockSize, int firstUbufSlot)
{
// draw the ground (the quad)
cb->setShaderResources(d.srb, { { 0, quint32(firstUbufSlot * oneRoundedUniformBlockSize) } });
cb->setVertexInput(0, { { d.vbuf, 0 } }, d.ibuf, 0, QRhiCommandBuffer::IndexUInt16);
cb->drawIndexed(6);
// Draw the object (the cube). Both vertex and uniform data are in the same
// buffer, right after the quad's.
cb->setShaderResources(d.srb, { qMakePair(0, quint32((firstUbufSlot + 1) * oneRoundedUniformBlockSize)) });
cb->setVertexInput(0, { { d.vbuf, sizeof(quadVertexData) } });
cb->draw(36);
}
void Window::customRender()
{
const QSize outputSizeInPixels = m_sc->currentPixelSize();
QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
QRhiResourceUpdateBatch *u = m_r->nextResourceUpdateBatch();
if (d.initialUpdates) {
u->merge(d.initialUpdates);
d.initialUpdates->release();
d.initialUpdates = nullptr;
}
const QVector3D lightPos(0, 10, 1); // must match the shader
const QVector3D shadowCamCenter(0, 0, 0);
const QVector3D shadowCamUp(0, 1, 0);
const int oneRoundedUniformBlockSize = m_r->ubufAligned(UBLOCK_SIZE);
// uniform data for the ground
if (d.winProj != m_proj) {
d.winProj = m_proj;
QMatrix4x4 m;
m.scale(4.0f);
m.rotate(-60, 1, 0, 0);
QMatrix4x4 mv;
mv.translate(0, 0, -4); // must match the shader
mv *= m;
// for the main pass
QMatrix4x4 mvp = m_r->clipSpaceCorrMatrix() * m_rawProj * mv;
u->updateDynamicBuffer(d.ubuf, 0, 64, mvp.constData());
mv = m_r->clipSpaceCorrMatrix() * mv;
u->updateDynamicBuffer(d.ubuf, 64, 64, mv.constData());
m = m_r->clipSpaceCorrMatrix() * m;
u->updateDynamicBuffer(d.ubuf, 128, 64, m.constData());
QMatrix3x3 n = m.normalMatrix();
u->updateDynamicBuffer(d.ubuf, 192, 48, n.constData());
// for the shadow pass
mvp = m_r->clipSpaceCorrMatrix();
mvp.perspective(45.0f, 1, 0.01f, 1000.0f);
mvp.lookAt(lightPos, shadowCamCenter, shadowCamUp);
mvp *= mv;
u->updateDynamicBuffer(d.ubuf, 2 * oneRoundedUniformBlockSize, 64, mvp.constData());
}
// uniform data for the rotating cube
QMatrix4x4 m;
m.translate(0, 1, 0);
m.scale(0.5f);
m.rotate(d.cubeRot, 1, 0, 0);
m.rotate(20, 0, 1, 0);
d.cubeRot += 1;
QMatrix4x4 mv;
mv.translate(0, 0, -4); // must match the shader
mv *= m;
// for the main pass
QMatrix4x4 mvp = m_r->clipSpaceCorrMatrix() * m_rawProj * mv;
u->updateDynamicBuffer(d.ubuf, oneRoundedUniformBlockSize, 64, mvp.constData());
mv = m_r->clipSpaceCorrMatrix() * mv;
u->updateDynamicBuffer(d.ubuf, oneRoundedUniformBlockSize + 64, 64, mv.constData());
m = m_r->clipSpaceCorrMatrix() * m;
u->updateDynamicBuffer(d.ubuf, oneRoundedUniformBlockSize + 128, 64, m.constData());
QMatrix3x3 n = m.normalMatrix();
u->updateDynamicBuffer(d.ubuf, oneRoundedUniformBlockSize + 192, 48, n.constData());
// for the shadow pass
mvp = m_r->clipSpaceCorrMatrix();
mvp.perspective(45.0f, 1, 0.01f, 1000.0f);
mvp.lookAt(lightPos, shadowCamCenter, shadowCamUp);
mvp *= mv;
u->updateDynamicBuffer(d.ubuf, 3 * oneRoundedUniformBlockSize, 64, mvp.constData());
cb->resourceUpdate(u);
// shadow pass
const QSize shadowMapSize = d.shadowMap->pixelSize();
cb->beginPass(d.rt, QRhiColorClearValue(), { 1.0f, 0 });
cb->setGraphicsPipeline(d.shadowPs);
cb->setViewport({ 0, 0, float(shadowMapSize.width()), float(shadowMapSize.height()) });
enqueueScene(cb, oneRoundedUniformBlockSize, 2);
cb->endPass();
// main pass
cb->beginPass(m_sc->currentFrameRenderTarget(), { 0.4f, 0.7f, 0.0f, 1.0f }, { 1.0f, 0 });
cb->setGraphicsPipeline(d.ps);
cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) });
enqueueScene(cb, oneRoundedUniformBlockSize, 0);
cb->endPass();
}
#version 440
void main()
{
}
TEMPLATE = app
QT += rhi
SOURCES = \
shadowmap.cpp
RESOURCES = shadowmap.qrc
target.path = $$[QT_INSTALL_EXAMPLES]/rhi/shadowmap
INSTALLS += target
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>shadowmap.vert.qsb</file>
<file>shadowmap.frag.qsb</file>
<file>light.vert.qsb</file>
<file>light.frag.qsb</file>
</qresource>
</RCC>
#version 440
layout(location = 0) in vec4 position;
layout(std140, binding = 0) uniform buf {
mat4 mvp;
} ubuf;
out gl_PerVertex { vec4 gl_Position; };
void main()
{
gl_Position = ubuf.mvp * position;
}
#ifndef CUBENORM_H
#define CUBENORM_H
// clang-format off
static const float cube[] = {
-1.0f,-1.0f,-1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 +157,7 @@ protected:
QRhiRenderPassDescriptor *m_rp = nullptr;
QMatrix4x4 m_proj;
QMatrix4x4 m_rawProj;
QElapsedTimer m_timer;
int m_frameCount;
......@@ -337,8 +338,9 @@ void Window::resizeSwapChain()
m_frameCount = 0;
m_timer.restart();
m_proj = m_r->clipSpaceCorrMatrix();
m_proj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
m_rawProj.setToIdentity();
m_rawProj.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
m_proj = m_r->clipSpaceCorrMatrix() * m_rawProj;
m_proj.translate(0, 0, -4);
}
......
......@@ -2782,6 +2782,28 @@ QRhiGraphicsPipeline::QRhiGraphicsPipeline(QRhiImplementation *rhi)
Regardless of the return value, calling release() is always safe.
*/
/*!
\fn void QRhiGraphicsPipeline::setDepthTest(bool enable)
Enables or disables depth testing. Both depth test and the writing out of
depth data are disabled by default.
\sa setDepthWrite()
*/
/*!
\fn void QRhiGraphicsPipeline::setDepthWrite(bool enable)
Controls the writing out of depth data into the depth buffer. By default
this is disabled. Depth write is typically enabled together with the depth
test.
\note Enabling depth write without having depth testing enabled may not
lead to the desired result, and should be avoided.
\sa setDepthTest()
*/
/*!
\class QRhiSwapChain
\inmodule QtRhi
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment