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
#include "Headers/CascadedShadowMaps.h"

#include "Core/Headers/ParamHandler.h"

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

#include "Managers/Headers/SceneManager.h"
#include "Managers/Headers/RenderPassManager.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(GFXDevice& context, Light* light, Camera* shadowCamera, U8 numSplits)
    : ShadowMap(context, 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;

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

    ResourceDescriptor blurDepthMapShader("blur.GaussBlur");
    blurDepthMapShader.setThreadedLoading(false);
    _blurDepthMapShader = CreateResource<ShaderProgram>(light->parentResourceCache(), blurDepthMapShader);
    _blurDepthMapShader->Uniform("layerTotalCount", (I32)_numSplits);
    _blurDepthMapShader->Uniform("layerCount",  (I32)_numSplits);

    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(Config::Lighting::MAX_SPLITS_PER_LIGHT);
    blurMapDescriptor.setSampler(blurMapSampler);
    
    _blurBuffer = _context.allocateRT("CSM_Blur");
    _blurBuffer._rt->addAttachment(blurMapDescriptor, RTAttachment::Type::Colour, 0);
    _blurBuffer._rt->setClearColour(RTAttachment::Type::COUNT, 0, DefaultColours::WHITE());

    ShaderBufferParams params;
    params._primitiveCount = Config::Lighting::MAX_SPLITS_PER_LIGHT;
    params._primitiveSizeInBytes = sizeof(mat4<F32>);
    params._ringBufferLength = 1;
    params._unbound = false;
    params._updateFrequency = BufferUpdateFrequency::OFTEN;

    _shadowMatricesBuffer = _context.newSB(params);

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

CascadedShadowMaps::~CascadedShadowMaps()
{
    _context.deallocateRT(_blurBuffer);
}

void CascadedShadowMaps::init(ShadowMapInfo* const smi) {
    _numSplits = smi->numLayers();
    const RenderTarget& depthMap = getDepthMap();
    _blurBuffer._rt->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(GFXDevice& context, U32 passIdx) {
    _splitLogFactor = _dirLight->csmSplitLogFactor();
    _nearClipOffset = _dirLight->csmNearClipOffset();
    _lightPosition.set(_light->getPosition());

    Camera& camera = *Camera::activeCamera();
    _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 (RenderPassCuller::VisibleNode node : nodes) {
        SceneGraphNode* node_ptr = node.second;
        if (node_ptr) {
            _previousFrustumBB.add(node_ptr->getBoundingBoxConst());
        }
    }
    _previousFrustumBB.transformHomogeneous(_shadowCamera->getViewMatrix());*/

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

    RenderPassManager::PassParams params;
    params.doPrePass = false;
    params.camera = _shadowCamera;
    params.stage = RenderStage::SHADOW;
    params.target = RenderTargetID(RenderTargetUsage::SHADOW, to_uint(getShadowMapType()));
    params.pass = passIdx;

    context.parent().renderPassManager().doCustomPass(params);

    postRender(context);
}

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(1.0f, minZ - _nearClipOffset), frustumSphereRadius * 2 + _nearClipOffset * 2);
        const mat4<F32>& projMatrix = _shadowCamera->setProjection(UNIT_RECT * frustumSphereRadius, clipPlanes);
        mat4<F32>::Multiply(viewMatrix, projMatrix, _shadowMatrices[pass]);

        // 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(GFXDevice& context) {
    if (context.shadowDetailLevel() == RenderDetailLevel::LOW) {
        return;
    }

    RenderTarget& depthMap = getDepthMap();

    _blurDepthMapShader->bind();

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

    // Blur horizontally
    _blurDepthMapShader->Uniform("layerOffsetRead", (I32)getArrayOffset());
    _blurDepthMapShader->Uniform("layerOffsetWrite", 0);

    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _horizBlur);
    _blurBuffer._rt->begin(RenderTarget::defaultPolicy());
    depthMap.bind(0, RTAttachment::Type::Colour, 0, false);
        context.draw(pointsCmd);
    depthMap.end();

    // Blur vertically
    _blurDepthMapShader->Uniform("layerOffsetRead", 0);
    _blurDepthMapShader->Uniform("layerOffsetWrite", (I32)getArrayOffset());

    _blurDepthMapShader->SetSubroutine(ShaderType::GEOMETRY, _vertBlur);
    depthMap.begin(RenderTarget::defaultPolicy());
    _blurBuffer._rt->bind(0, RTAttachment::Type::Colour, 0);
        context.draw(pointsCmd);
    depthMap.end();
}

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

    getDepthMap().bind(to_const_ubyte(ShaderProgram::TextureUsage::UNIT0), RTAttachment::Type::Colour, 0);

    GenericDrawCommand triangleCmd;
    triangleCmd.primitiveType(PrimitiveType::TRIANGLES);
    triangleCmd.drawCount(1);
    triangleCmd.stateHash(context.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(context, viewport.x * i, viewport.y, viewport.z, viewport.w);
        context.draw(triangleCmd);
    }
}
};

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

Diff revisions: vs.
Revision Author Commited Message
827 Diff Diff IonutCava picture IonutCava Sun 22 Jan, 2017 21:59:36 +0000

[IonutCava]
- ShaderBuffers now decide heuristically if they get persistently mapped or not (depends on size. Current limit is 512Kb for subData calls.
- Separate visible node command generation into 2 steps: onRender and getDrawPackage. onRender allows the creation of parallel tasks that should finish by the time the second call, getDrawPackage reaches the same node
- Update ParticleEmitter to take into account multiple players and increase parallelism at the cost of memory consumption and complexity.
- Add a default bounding box for Players (add extents to SceneTransform nodes)
- All buffers (ShaderBuffer, d3dConstantBuffer, glUniformBuffer, glBufferImpl, glGenericBuffer, etc) use BufferParams for creation.
— Constructor and create calls have been merged together

824 Diff Diff IonutCava picture IonutCava Thu 19 Jan, 2017 17:18:03 +0000

[IonutCava]
- Prev Frame attachment system removed from RenderTargets
— Concept too high level for RT. Moved prev depth buffer to GFX class
- Other small optimizations.

816 Diff Diff IonutCava picture IonutCava Fri 13 Jan, 2017 17:05:20 +0000

[IonutCava]
- Allow per player scene state and input source
— Add SceneStatePerPlayer class
— Add device index to InputParams objects.
— ToDo: map players to devide indices

815 Diff Diff IonutCava picture IonutCava Thu 12 Jan, 2017 23:33:01 +0000

[IonutCava]
- Fixed viewport alignment issue
- Added per-player RenderTargets (added index support to GFXRTPool)
- Initial implementation of per-player cameras
— Removed defaultCamera
— Scenes now use a baseCamera as a template for new player cameras

807 Diff Diff IonutCava picture IonutCava Mon 09 Jan, 2017 17:06:26 +0000

[IonutCava]
- Split PlatformDefines.h into 2. Move data type defines to PlatformDataTypes.h
- Continue to improve velocity map calculation
- Remove “destroy()” calls from most classes. Attempt to move as many classes to the RAII system.

804 Diff Diff IonutCava picture IonutCava Thu 01 Dec, 2016 17:20:59 +0000

[IonutCava]
- Singleton elimination update Part I: get it to compile
— The following classes are no longer Singletons: GFXDevice, GL_API, DX_API, SFXWrapper, FmodWrapper, SDLWrapper, ALWrapper, PXDevice, InputInterface, RenderPassManager, SceneManager and ResourceManager;
— Refactor system to a Context / Component based implementation (Pass relevant context to objects: e.g. GFXDevice object to Textures, GUI to GUIElements, etc)
— Make devices and managers components of the kernel
— Allow multiple Resource caches to co-exist. This may prove useful for later when a more fragmented memory model is need (per frame / per scene / global caches / etc)

  • next steps: part II – cleanup/refactor new code, part III – optimise code, part IV – remove remaining Singletons (e.g. Application, ParamHandler, FrameListenerManager, Recast, PostFX and DebugInterface)
801 Diff Diff IonutCava picture IonutCava Sun 27 Nov, 2016 21:28:01 +0000

[IonutCava]
- More performance analysis guided optimizations.
- Some refactoring to allow later removal of Singletons status for: GFXDevice, SFXDevice, PXDevice, GUI and Input.
— Pass a PlatformContext around objects to access these classes.

792 Diff Diff IonutCava picture IonutCava Fri 18 Nov, 2016 16:08:45 +0000

[IonutCava]
- Allow RenderTarget attachments to keep the previous frame’s rendering result automatically. Specify if history should be saved via a bool flag on addition to the RenderTarget.

791 Diff Diff IonutCava picture IonutCava Thu 17 Nov, 2016 16:46:19 +0000

[IonutCava]
- Reworked PostFX filter list to allow multiple enable calls to the same effect (stack based)
- Added noise, vignette and underwater effects to the filter list available for PostFX
- Added better underwater camera detection

788 IonutCava picture IonutCava Fri 21 Oct, 2016 16:11:37 +0000

[IonutCava]
- Added support for the Arena Allocator by Mamasha Knows (http://www.codeproject.com/Articles/44850/Arena-Allocator-DTOR-and-Embedded-Preallocated-Buf)
— Used for GFX Related objects: Textures, shaders, etc