Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#include "Headers/CascadedShadowMaps.h"

#include "Core/Headers/ParamHandler.h"

#include "Scenes/Headers/SceneState.h"

#include "Rendering/Headers/Renderer.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Rendering/Lighting/Headers/Light.h"

#include "Managers/Headers/LightManager.h"
#include "Managers/Headers/SceneManager.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Shaders/Headers/ShaderManager.h"

#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"

namespace Divide {

CascadedShadowMaps::CascadedShadowMaps(Light* light, Camera* shadowCamera,
                                       U8 numSplits)
    : ShadowMap(light, shadowCamera, ShadowType::LAYERED)
{
    _dirLight = dynamic_cast<DirectionalLight*>(_light);
    _splitLogFactor = 0.0f;
    _nearClipOffset = 0.0f;
    _numSplits = numSplits;
    _splitDepths.resize(_numSplits + 1);
    _frustumCornersWS.resize(8);
    _frustumCornersVS.resize(8);
    _frustumCornersLS.resize(8);
    _splitFrustumCornersVS.resize(8);
    _horizBlur = 0;
    _vertBlur = 0;
    _renderPolicy = MemoryManager_NEW Framebuffer::FramebufferTarget(
        Framebuffer::defaultPolicy());
    // We clear the FB on each face draw call, not on Begin()
    _renderPolicy->_clearBuffersOnBind = false;

    ResourceDescriptor shadowPreviewShader("fbPreview.Layered.LinearDepth.ESM.ScenePlanes");
    shadowPreviewShader.setThreadedLoading(false);
    shadowPreviewShader.setPropertyList("USE_SCENE_ZPLANES");
    _previewDepthMapShader = CreateResource<ShaderProgram>(shadowPreviewShader);
    _previewDepthMapShader->Uniform("useScenePlanes", false);

    ResourceDescriptor blurDepthMapShader("blur.GaussBlur");
    blurDepthMapShader.setThreadedLoading(false);
    _blurDepthMapShader = CreateResource<ShaderProgram>(blurDepthMapShader);
    _blurDepthMapShader->Uniform("texScreen", ShaderProgram::TextureUsage::UNIT0);
    _blurDepthMapShader->Uniform("layerTotalCount", (I32)_numSplits);
    _blurDepthMapShader->Uniform("layerCount", (I32)_numSplits - 1);
    _blurDepthMapShader->Uniform("layerOffset", (I32)0);

    Console::printfn(Locale::get("LIGHT_CREATE_SHADOW_FB"), light->getGUID(), "EVCSM");

    SamplerDescriptor depthMapSampler;
    depthMapSampler.setFilters(TextureFilter::LINEAR_MIPMAP_LINEAR);
    depthMapSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    depthMapSampler.setAnisotropy(8);
    TextureDescriptor depthMapDescriptor(TextureType::TEXTURE_2D_ARRAY,
                                         GFXImageFormat::RG32F,
                                         GFXDataFormat::FLOAT_32);
    depthMapDescriptor.setLayerCount(_numSplits);
    depthMapDescriptor.setSampler(depthMapSampler);

    _depthMap = GFX_DEVICE.newFB(false);
    _depthMap->addAttachment(depthMapDescriptor,
                             TextureDescriptor::AttachmentType::Color0);
    _depthMap->setClearColor(DefaultColors::WHITE());

    SamplerDescriptor blurMapSampler;
    blurMapSampler.setFilters(TextureFilter::LINEAR);
    blurMapSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    depthMapSampler.setAnisotropy(0);
    blurMapSampler.toggleMipMaps(false);
    TextureDescriptor blurMapDescriptor(TextureType::TEXTURE_2D_ARRAY,
                                        GFXImageFormat::RG32F,
                                        GFXDataFormat::FLOAT_32);
    blurMapDescriptor.setLayerCount(_numSplits);
    blurMapDescriptor.setSampler(blurMapSampler);
    
    _blurBuffer = GFX_DEVICE.newFB(false);
    _blurBuffer->addAttachment(blurMapDescriptor,
                               TextureDescriptor::AttachmentType::Color0);
    _blurBuffer->setClearColor(DefaultColors::WHITE());

    _shadowMatricesBuffer.reset(GFX_DEVICE.newSB("dvd_shadowMatrices", 1, false, false, BufferUpdateFrequency::OFTEN));
    _shadowMatricesBuffer->create(Config::Lighting::MAX_SPLITS_PER_LIGHT, sizeof(mat4<F32>));
}

CascadedShadowMaps::~CascadedShadowMaps()
{
    RemoveResource(_previewDepthMapShader);
    RemoveResource(_blurDepthMapShader);
    MemoryManager::DELETE(_blurBuffer);
    MemoryManager::DELETE(_renderPolicy);
}

void CascadedShadowMaps::init(ShadowMapInfo* const smi) {
    _numSplits = smi->numLayers();
    resolution(smi->resolution(), _light->shadowMapResolutionFactor());
    _init = true;
}

void CascadedShadowMaps::resolution(U16 resolution, U8 resolutionFactor) {
    U16 tempResolution = resolution * resolutionFactor;
    if (_resolution != tempResolution) {
        _resolution = tempResolution;
        // Initialize the FB's with a variable resolution
        Console::printfn(Locale::get("LIGHT_INIT_SHADOW_FB"), _light->getGUID());
        _depthMap->create(_resolution, _resolution);
        _blurBuffer->create(_resolution, _resolution);

        _blurDepthMapShader->bind();
        _horizBlur = _blurDepthMapShader->GetSubroutineIndex(ShaderType::GEOMETRY, "computeCoordsH");
        _vertBlur = _blurDepthMapShader->GetSubroutineIndex(ShaderType::GEOMETRY, "computeCoordsV");

        vectorImpl<vec2<F32>> blurSizes(_numSplits);
        blurSizes[0].set(1.0f / (_depthMap->getWidth() * 1.0f),
                         1.0f / (_depthMap->getHeight() * 1.0f));
        for (int i = 1; i < _numSplits; ++i) {
            blurSizes[i].set(blurSizes[i - 1] / 2.0f);
        }

        _blurDepthMapShader->Uniform("blurSizes", blurSizes);
    }

    ShadowMap::resolution(resolution, resolutionFactor);
}

void CascadedShadowMaps::render(SceneRenderState& renderState) {
    _splitLogFactor = _dirLight->csmSplitLogFactor();
    _nearClipOffset = _dirLight->csmNearClipOffset();
    _lightPosition.set(_light->getPosition());

    Camera& camera = renderState.getCamera();
    _sceneZPlanes.set(camera.getZPlanes());
    camera.getWorldMatrix(_viewInvMatrixCache);
    camera.getFrustum().getCornersWorldSpace(_frustumCornersWS);
    camera.getFrustum().getCornersViewSpace(_frustumCornersVS);

    calculateSplitDepths(camera);
    applyFrustumSplits();

    /*const RenderPassCuller::VisibleNodeList& nodes = 
        SceneManager::getInstance().cullSceneGraph(RenderStage::SHADOW);

    _previousFrustumBB.reset();
    for (SceneGraphNode_wptr node_wptr : nodes) {
        SceneGraphNode_ptr node_ptr = node_wptr.lock();
        if (node_ptr) {
            _previousFrustumBB.add(node_ptr->getBoundingBoxConst());
        }
    }
    _previousFrustumBB.transform(_shadowCamera->getViewMatrix());*/

    _shadowMatricesBuffer->setData(_shadowMatrices.data());
    _shadowMatricesBuffer->bind(ShaderBufferLocation::LIGHT_SHADOW);
    _shadowMatricesBuffer->incQueue();

    renderState.getCameraMgr().pushActiveCamera(_shadowCamera, false);
    _depthMap->begin(Framebuffer::defaultPolicy());
        SceneManager::getInstance().render(RenderStage::SHADOW, Application::getInstance().getKernel(), true, true);
    _depthMap->end();
    renderState.getCameraMgr().popActiveCamera();
}

void CascadedShadowMaps::calculateSplitDepths(const Camera& cam) {
    const mat4<F32>& projMatrixCache = cam.getProjectionMatrix();

    F32 fd = _sceneZPlanes.y;//std::min(_sceneZPlanes.y, _previousFrustumBB.getExtent().z);
    F32 nd = _sceneZPlanes.x;//std::max(_sceneZPlanes.x, std::fabs(_previousFrustumBB.nearestDistanceFromPoint(cam.getEye())));

    F32 i_f = 1.0f, cascadeCount = (F32)_numSplits;
    _splitDepths[0] = nd;
    for (U32 i = 1; i < to_uint(_numSplits); ++i, i_f += 1.0f)
    {
        _splitDepths[i] = Lerp(nd + (i_f / cascadeCount)*(fd - nd),  nd * std::powf(fd / nd, i_f / cascadeCount), _splitLogFactor);
    }
    _splitDepths[_numSplits] = fd;

    for (U8 i = 0; i < Config::Lighting::MAX_SPLITS_PER_LIGHT; ++i) {
        if (i < _numSplits) {
            _light->setShadowFloatValue(i, 0.5f * (-_splitDepths[i + 1] * projMatrixCache.mat[10] + projMatrixCache.mat[14]) / _splitDepths[i + 1] + 0.5f);
        } else {
            _light->setShadowFloatValue(i, 1.0f);
        }
    }
}

void CascadedShadowMaps::applyFrustumSplits() {
    for (U8 pass = 0 ; pass < _numSplits; ++pass) {
        F32 minZ = _splitDepths[pass];
        F32 maxZ = _splitDepths[pass + 1];

        for (U8 i = 0; i < 4; ++i) {
            _splitFrustumCornersVS[i] =
                _frustumCornersVS[i + 4] * (minZ / _sceneZPlanes.y);
        }

        for (U8 i = 4; i < 8; ++i) {
            _splitFrustumCornersVS[i] =
                _frustumCornersVS[i] * (maxZ / _sceneZPlanes.y);
        }

        for (U8 i = 0; i < 8; ++i) {
            _frustumCornersWS[i].set(
                _viewInvMatrixCache.transform(_splitFrustumCornersVS[i]));
        }

        vec3<F32> frustumCentroid(0.0f);

        for (U8 i = 0; i < 8; ++i) {
            frustumCentroid += _frustumCornersWS[i];
        }
        // Find the centroid
        frustumCentroid /= 8;

        // Position the shadow-caster camera so that it's looking at the centroid,
        // and backed up in the direction of the sunlight
        F32 distFromCentroid = std::max((maxZ - minZ),
                     _splitFrustumCornersVS[4].distance(_splitFrustumCornersVS[5])) + _nearClipOffset;
    
        vec3<F32> currentEye = frustumCentroid - (_lightPosition * distFromCentroid);

        const mat4<F32>& viewMatrix = _shadowCamera->lookAt(currentEye, frustumCentroid);
        // Determine the position of the frustum corners in light space
        for (U8 i = 0; i < 8; ++i) {
            _frustumCornersLS[i].set(viewMatrix.transform(_frustumCornersWS[i]));
        }

        F32 frustumSphereRadius = BoundingSphere(_frustumCornersLS).getRadius();
        vec2<F32> clipPlanes(std::max(0.0f, minZ - _nearClipOffset), (frustumSphereRadius * 2) + _nearClipOffset);
        _shadowCamera->setProjection(UNIT_RECT * frustumSphereRadius,
                                     clipPlanes,
                                     true);
        _shadowMatrices[pass].set(viewMatrix * _shadowCamera->getProjectionMatrix());

        // http://www.gamedev.net/topic/591684-xna-40---shimmering-shadow-maps/
        F32 halfShadowMapSize = (_resolution)*0.5f;
        vec3<F32> testPoint = _shadowMatrices[pass].transform(VECTOR3_ZERO) * halfShadowMapSize;
        vec3<F32> testPointRounded(testPoint);
        testPointRounded.round();
        vec3<F32> rounding = (testPointRounded - testPoint) / halfShadowMapSize;

        _light->setShadowVPMatrix(pass, mat4<F32>(rounding.x, rounding.y, 0.0f) * _shadowMatrices[pass] * _bias);
        _light->setShadowLightPos(pass, currentEye);
    }
}

void CascadedShadowMaps::postRender() {
    if (GFX_DEVICE.shadowDetailLevel() == RenderDetailLevel::LOW) {
        return;
    }
    _blurDepthMapShader->bind();

    // Blur horizontally
    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _horizBlur);
    _blurBuffer->begin(Framebuffer::defaultPolicy());
    _depthMap->bind(0, TextureDescriptor::AttachmentType::Color0, false);
        GFX_DEVICE.drawPoints(1, GFX_DEVICE.getDefaultStateBlock(true), _blurDepthMapShader);
    _blurBuffer->end();

    // Blur vertically
    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _vertBlur);
    _depthMap->begin(Framebuffer::defaultPolicy());
    _blurBuffer->bind();
        GFX_DEVICE.drawPoints(1, GFX_DEVICE.getDefaultStateBlock(true), _blurDepthMapShader);
    _depthMap->end();
}

bool CascadedShadowMaps::bindInternal(U8 offset) {
    _depthMap->bind(offset);
    return true;
}

void CascadedShadowMaps::previewShadowMaps() {
    if (_previewDepthMapShader->getState() != ResourceState::RES_LOADED) {
        return;
    }

    U32 stateHash = GFX_DEVICE.getDefaultStateBlock(true);
    _depthMap->bind();
    for (U32 i = 0; i < _numSplits; ++i) {
        _previewDepthMapShader->Uniform("layer", i);
        _previewDepthMapShader->Uniform("dvd_zPlanes", _splitDepths[i]);

        GFX::ScopedViewport viewport(256 * i, 1, 256, 256);
        GFX_DEVICE.drawTriangle(stateHash, _previewDepthMapShader);
    }
}
};

Commits for Divide-Framework/trunk/Source Code/Rendering/Lighting/ShadowMapping/CascadedShadowMaps.cpp

Diff revisions: vs.
Revision Author Commited Message
557 Diff Diff IonutCava picture IonutCava Tue 10 Nov, 2015 12:00:20 +0000

[IonutCava]
- Gather all rendering calls from glVertexArray and glGenericVertexData into a single function in glResources: submitRenderCommand.
— This allows both classes to interpret GenericDrawCommands in the same way
- Use unsigned ints for all hasehs instead of size_t to avoid negative number hashes (useful for debugging)

553 Diff Diff IonutCava picture IonutCava Sun 08 Nov, 2015 21:48:10 +0000

[IonutCava]
- Improve VBO allocation system
- Disable mipmap generation for blur FBO in CascadedShadowMaps
- Code cleanup

552 Diff Diff IonutCava picture IonutCava Fri 06 Nov, 2015 17:07:22 +0000

[Ionut]
- Use UNIT0 and UNIT1 during depth pass for transparency texture to reduce texture binds between calls
- Allow different VAOs with different attributes per render stage per glVertexArray instance
- Initial work on multiple glVertexArray instances per single VBO (attempt to get VBOs to the 4MB mark) - Currently crashes the build
- Fix a bug on exit if background tasks depended on scene elements. Wait for the main threadpool to clear before destroying the scene.
- Use a different node buffer per rendering stage to avoid waiting too much on fence syncs

551 Diff Diff IonutCava picture IonutCava Thu 05 Nov, 2015 17:08:03 +0000

[IonutCava]
- Streamline RenderPass/RenderBin/RenderPassCuller logic:
— Separate culling from updating nodes
— Improve sorting and batching
- Cleanups and sanity checks
- Replace some std::bind calls with lambdas

548 Diff Diff IonutCava picture IonutCava Wed 04 Nov, 2015 17:23:15 +0000

[IonutCava]
- More work on improving cascaded shadow maps

546 Diff Diff IonutCava picture IonutCava Tue 03 Nov, 2015 23:40:35 +0000

[IonutCava]
- Single pass (layered rendering) cascaded shadowmaps including blur
- Naming convention fixes

545 Diff Diff IonutCava picture IonutCava Tue 03 Nov, 2015 17:15:43 +0000

[IonutCava]
- Reimplement single pass layered shadow rendering
- Cleanup frambuffer class and use clearBuffer instead of clearColor.
- Clean ShaderProgram uniform calls a bit

544 Diff Diff IonutCava picture IonutCava Fri 30 Oct, 2015 23:56:42 +0000

[Ionut]
- Reverted some of the changes as they caused too many issues for now

543 Diff Diff IonutCava picture IonutCava Fri 30 Oct, 2015 17:18:18 +0000

[IonutCava]
- More profile guided optimizations
- Attempt to render all CSM splits in a single pass using geometry shader based instancing (unfinished)

529 IonutCava picture IonutCava Mon 19 Oct, 2015 20:34:35 +0000

[IonutCava]
- Some alignment fixes
- Removed some redundant shader binds