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
#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/SceneManager.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"

#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.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 RTDrawDescriptor(RenderTarget::defaultPolicy());
    // We clear the FB on each face draw call, not on Begin()
    _renderPolicy->_clearDepthBufferOnBind = false;
    _renderPolicy->_clearColourBuffersOnBind = 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("layerTotalCount", (I32)_numSplits);
    _blurDepthMapShader->Uniform("layerCount", (I32)_numSplits - 1);
    _blurDepthMapShader->Uniform("layerOffset", (I32)getArrayOffset());

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

    SamplerDescriptor blurMapSampler;
    blurMapSampler.setFilters(TextureFilter::LINEAR);
    blurMapSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    blurMapSampler.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.newRT(false);
    _blurBuffer->addAttachment(blurMapDescriptor,
                               RTAttachment::Type::Colour, 0);
    _blurBuffer->setClearColour(RTAttachment::Type::COUNT, 0, DefaultColours::WHITE());

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

    STUBBED("Migrate to this: http://www.ogldev.org/www/tutorial49/tutorial49.html");
}

CascadedShadowMaps::~CascadedShadowMaps()
{
    MemoryManager::DELETE(_blurBuffer);
    MemoryManager::DELETE(_renderPolicy);
    MemoryManager::DELETE(_shadowMatricesBuffer);
}

void CascadedShadowMaps::init(ShadowMapInfo* const smi) {
    _numSplits = smi->numLayers();
    RenderTarget* depthMap = getDepthMap();
    _blurBuffer->create(depthMap->getWidth(), depthMap->getHeight());
    _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);

    _init = true;
}

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::instance().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.transformHomogeneous(_shadowCamera->getViewMatrix());*/

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

    renderState.getCameraMgr().pushActiveCamera(_shadowCamera);
    getDepthMap()->begin(*_renderPolicy);
        SceneManager::instance().renderVisibleNodes(RenderStage::SHADOW, true);
    getDepthMap()->end();
    renderState.getCameraMgr().popActiveCamera();

    postRender();
}

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 < _numSplits; ++i) {
        F32 crtSplitDepth = 0.5f * (-_splitDepths[i + 1] * projMatrixCache.mat[10] + projMatrixCache.mat[14]) / _splitDepths[i + 1] + 0.5f;
       _light->setShadowFloatValue(i, crtSplitDepth);
    }
}

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.transformHomogeneous(_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.transformHomogeneous(_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 = (getDepthMap()->getWidth())*0.5f;
        vec3<F32> testPoint = _shadowMatrices[pass].transformHomogeneous(VECTOR3_ZERO) * halfShadowMapSize;
        vec3<F32> testPointRounded(testPoint);
        testPointRounded.round();
        _shadowMatrices[pass].translate(vec3<F32>(((testPointRounded - testPoint) / halfShadowMapSize).xy(), 0.0f));

        _light->setShadowVPMatrix(pass, _shadowMatrices[pass] * MAT4_BIAS);
        _light->setShadowLightPos(pass, currentEye);
    }
}

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

    GenericDrawCommand pointsCmd;
    pointsCmd.primitiveType(PrimitiveType::API_POINTS);
    pointsCmd.drawCount(1);
    pointsCmd.stateHash(GFX_DEVICE.getDefaultStateBlock(true));
    pointsCmd.shaderProgram(_blurDepthMapShader);

    // Blur horizontally
    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _horizBlur);
    _blurBuffer->begin(RenderTarget::defaultPolicy());
    getDepthMap()->bind(0, RTAttachment::Type::Colour, 0, false);
        GFX_DEVICE.draw(pointsCmd);
    getDepthMap()->end();

    // Blur vertically
    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _vertBlur);
    getDepthMap()->begin(RenderTarget::defaultPolicy());
    _blurBuffer->bind(0, RTAttachment::Type::Colour, 0);
        GFX_DEVICE.draw(pointsCmd);
    getDepthMap()->end();
}

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


    getDepthMap()->bind(0, RTAttachment::Type::Colour, 0);

    GenericDrawCommand triangleCmd;
    triangleCmd.primitiveType(PrimitiveType::TRIANGLES);
    triangleCmd.drawCount(1);
    triangleCmd.stateHash(GFX_DEVICE.getDefaultStateBlock(true));
    triangleCmd.shaderProgram(_previewDepthMapShader);

    const vec4<I32> viewport = getViewportForRow(rowIndex);
    for (U32 i = 0; i < _numSplits; ++i) {
        _previewDepthMapShader->Uniform("layer", i + _arrayOffset);
        GFX::ScopedViewport sViewport(viewport.x * i, viewport.y, viewport.z, viewport.w);
        GFX_DEVICE.draw(triangleCmd);
    }
}
};

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

Diff revisions: vs.
Revision Author Commited Message
727 Diff Diff IonutCava picture IonutCava Tue 14 Jun, 2016 16:01:38 +0000

[IonutCava]
- Remove node and cmd buffers from GFXDevice and add them as a new BufferData struct to RenderPass class.
— Each render pass holds its own buffers
- Improvements / fixes to the CSM code
- Added a global toggle to enable/disable custom memory allocators

725 Diff Diff IonutCava picture IonutCava Fri 10 Jun, 2016 12:44:46 +0000

[IonutCava]
- Removed GFX drawPoints and drawTriangle calls and replaced them with a single draw command that takes a GenericDrawCommand parameter.
- Updated CSM code. Shadows now render in the correct position again. Still has issues.

722 Diff Diff IonutCava picture IonutCava Thu 09 Jun, 2016 16:15:33 +0000

[IonutCava]
- Restructure RenderTarget system:
— Separate attachments, use an attachment pool, use draw descriptors, require explicit information for RT calls, etc

721 Diff Diff IonutCava picture IonutCava Wed 08 Jun, 2016 15:47:49 +0000

[IonutCava]
- Spelling: change all references from our code of “color” to the PROPER British version of “colour” because it sounds 100x better

718 Diff Diff IonutCava picture IonutCava Thu 02 Jun, 2016 16:02:48 +0000

[IonutCava]
- Code cleanup:
— Rename Framebuffer to RenderTarget. Only OpenGL uses the Framebuffer nomenclature.
— Remove base Shader class as only OpenGL will have separate shaders (and eventually move to pipeline objects) as Direct3D uses FX files and may end up with different structure
— Remove drawBox3D, drawSphere3D and drawLines from GFXDevice class and add them as member functions to the IMPrimitive class (renamed to fromXYZ)
— Pull some elements from SceneManager and move them to standalone classes (W.I.P.)

716 Diff Diff IonutCava picture IonutCava Tue 31 May, 2016 16:08:29 +0000

[IonutCava]
- Multithreaded scene load/unload fixes:
— Added postLoadMainThread call for scenes for thread sensitive loading steps
— GUI element adding is a thread sensitive loading step (a fast one) because CEGUI doesn’t handle threading
- Added REALTIME_WITH_CALLBACK task priority for tasks that need an immediate callback when they complete instead of using the flushCallbackQueue system.
- Some work on shadow mapping for getting it to work again
- ShaderPrograms that fail to load can cause a LockManager infinite wait. Delete the lockManager if the shader didn’t load to avoid waiting on commands that never get called.

713 Diff Diff IonutCava picture IonutCava Wed 25 May, 2016 15:43:38 +0000

[IonutCava]
- Removed all unique_ptr’s from the code with classic new/delete pairs. They were seriously not needed.
- Added the concept of SceneComponent to scene specific classes: aiManager, lightPool, sceneGraph, physicsInterface etc
— This allowed the removal of the global GET_ACTIVE_SCENEGRAPH call;

709 Diff Diff IonutCava picture IonutCava Thu 19 May, 2016 16:21:46 +0000

[IonutCava]
- Massive rewrite of the resource system:
— ResourceCache now uses a map of weak pointers and passes shared pointers to the call point of CreateResource
— RemoveResource is no longer needed, but resource based smart pointers use a custom deleter that calls unload()
— Keep a shared_ptr of the resource in the entity that needs it and pass shared_ptr references from getter methods
-— All of this removed the need for calls to RemoveResource, REGISTER_TRACKED_DEPENDENCY and UNREGISTER_TRACKED_DEPENDENCY reducing the number of mutex locks and atomic exchanges
- Singleton cleanup:
— Removed ShaderManager singleton and merged it’s data and responsibilities in static methods in both ShaderProgram and Shader classes.
Explanation: Due to the complex interdependency chains in the system, copying, updating, tracking the cache in a thread safe way became a lot more slower than a straight forward smart pointer based implementation. (e.g. scene graph nodes have 3d objects and material instances, 3d objects have materials, materials have textures and shaders, etc)

706 Diff Diff IonutCava picture IonutCava Fri 13 May, 2016 16:29:40 +0000

[IonutCava]
- Renamed LightManager to LightPool and changed it from a Singleton to a scene specific pointer
- More scene load / unload updates (changing scenes now works properly!)
- Allowed GUI interface to hold per-scene elements and only render relevant ones
- Reduced dependencies between nodes, scenemanager, scene, loaders and kernel
- Removed Reflector base class as it was useless and integrate Water class with the Reflection system already in place
- Extended RenderingComponent’s reflection system to allow refraction as well

703 IonutCava picture IonutCava Wed 11 May, 2016 15:44:57 +0000

[IonutCava]
- Finish XML-based control bindings:
— Allow per bind input params (key id, mouse button index, joystick control data, etc)
— Allow mouse binding (with up to 7 buttons)
— Allow up to 4 joysticks (for now) with 120+ button, POV, Axis, Slider and Vector binding support for each
- Change all hashes in code from U32 to size_t for compatibility with STL/Boost