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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#include "stdafx.h"

#include "Headers/LightPool.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/StringHelper.h"
#include "Core/Time/Headers/ProfileTimer.h"
#include "Managers/Headers/SceneManager.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Platform/Video/Textures/Headers/Texture.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Rendering/Lighting/ShadowMapping/Headers/ShadowMap.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Platform/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.h"

namespace Divide {

std::array<U8, to_base(ShadowType::COUNT)> LightPool::_shadowLocation = { {
    to_U8(ShaderProgram::TextureUsage::SHADOW_SINGLE),
    to_U8(ShaderProgram::TextureUsage::SHADOW_LAYERED),
    to_U8(ShaderProgram::TextureUsage::SHADOW_CUBE)
}};

Light* LightPool::_currentShadowCastingLight = nullptr;

bool LightPool::_previewShadowMaps = false;

LightPool::LightPool(Scene& parentScene, GFXDevice& context)
    : SceneComponent(parentScene),
      _context(context),
      _init(false),
      _buffersUpdated(false),
      _lightImpostorShader(nullptr),
      _lightIconsTexture(nullptr),
     // shadowPassTimer is used to measure the CPU-duration of shadow map generation step
     _shadowPassTimer(Time::ADD_TIMER("Shadow Pass Timer"))
{
    _activeLightCount.fill(0);
    _lightTypeState.fill(true);
    // NORMAL holds general info about the currently active
    // lights: position, colour, etc.
    _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)] = nullptr;
    // SHADOWS holds info about the currently active shadow
    // casting lights:
    // ViewProjection Matrices, View Space Position, etc
    _lightShaderBuffer[to_base(ShaderBufferType::SHADOW)] = nullptr;

    ParamHandler::instance().setParam<bool>(_ID("rendering.debug.displayShadowDebugInfo"), false);

    _sortedLights.reserve(Config::Lighting::MAX_POSSIBLE_LIGHTS);
    _sortedShadowCastingLights.reserve(Config::Lighting::MAX_SHADOW_CASTING_LIGHTS);
    _sortedLightProperties.reserve(Config::Lighting::MAX_POSSIBLE_LIGHTS);
    _sortedShadowProperties.reserve(Config::Lighting::MAX_SHADOW_CASTING_LIGHTS);

    init();
}

LightPool::~LightPool()
{
    clear();
}

void LightPool::init() {
    if (_init) {
        return;
    }

    ShaderBufferDescriptor bufferDescriptor;
    bufferDescriptor._primitiveCount = Config::Lighting::MAX_POSSIBLE_LIGHTS;
    bufferDescriptor._primitiveSizeInBytes = sizeof(LightProperties);
    bufferDescriptor._ringBufferLength = 1;
    bufferDescriptor._unbound = true;
    bufferDescriptor._updateFrequency = BufferUpdateFrequency::OCASSIONAL;

    // NORMAL holds general info about the currently active lights: position, colour, etc.
    _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)] = _context.newSB(bufferDescriptor);

    // SHADOWS holds info about the currently active shadow casting lights:
    // ViewProjection Matrices, View Space Position, etc
    // Should be SSBO (not UBO) to use std430 alignment. Structures should not be padded
    bufferDescriptor._primitiveCount = Config::Lighting::MAX_SHADOW_CASTING_LIGHTS;
    bufferDescriptor._primitiveSizeInBytes = sizeof(Light::ShadowProperties);
    _lightShaderBuffer[to_base(ShaderBufferType::SHADOW)] = _context.newSB(bufferDescriptor);

    ResourceDescriptor lightImpostorShader("lightImpostorShader");
    lightImpostorShader.setThreadedLoading(false);
    _lightImpostorShader = CreateResource<ShaderProgram>(_parentScene.resourceCache(), lightImpostorShader);

    SamplerDescriptor iconSampler;
    iconSampler.toggleMipMaps(false);
    iconSampler.setAnisotropy(0);
    iconSampler.setWrapMode(TextureWrap::REPEAT);
    ResourceDescriptor iconImage("LightIconTexture");
    iconImage.setThreadedLoading(false);
    iconImage.setPropertyDescriptor<SamplerDescriptor>(iconSampler);
    iconImage.setResourceLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
    iconImage.setResourceName("lightIcons.png");
    iconImage.setEnumValue(to_base(TextureType::TEXTURE_2D));
    _lightIconsTexture = CreateResource<Texture>(_parentScene.resourceCache(), iconImage);

    _init = true;
}

bool LightPool::clear() {
    if (!_init) {
        return true;
    }

    SceneGraph& sceneGraph = _parentScene.sceneGraph();
    for (Light::LightList& lightList : _lights) {
        // Lights are removed by the sceneGraph
        // (range_based for-loops will fail due to iterator invalidation
        vectorAlg::vecSize lightCount = lightList.size();
        for (vectorAlg::vecSize i = lightCount; i--> 0;) {
            Light* crtLight = lightList[i];
            sceneGraph.getRoot().removeNode(*crtLight->getSGN());

        }
        lightList.clear();
    }
    _init = false;
    
    return true;
}

bool LightPool::addLight(Light& light) {
    light.addShadowMapInfo(MemoryManager_NEW ShadowMapInfo(&light));

    const LightType type = light.getLightType();
    const U32 lightTypeIdx = to_base(type);

    if (findLight(light.getGUID(), type) != std::end(_lights[lightTypeIdx])) {

        Console::errorfn(Locale::get(_ID("ERROR_LIGHT_POOL_DUPLICATE")),
                         light.getGUID());
        return false;
    }

    vectorAlg::emplace_back(_lights[lightTypeIdx], &light);

    return true;
}

// try to remove any leftover lights
bool LightPool::removeLight(I64 lightGUID, LightType type) {
    Light::LightList::const_iterator it = findLight(lightGUID, type);

    if (it == std::end(_lights[to_U32(type)])) {
        Console::errorfn(Locale::get(_ID("ERROR_LIGHT_POOL_REMOVE_LIGHT")),
                         lightGUID);
        return false;
    }

    _lights[to_U32(type)].erase(it);  // remove it from the map
    return true;
}

void LightPool::idle() {
}

/// When pre-rendering is done, the Light Manager will generate the shadow maps
/// Returning false in any of the FrameListener methods will exit the entire
/// application!
bool LightPool::generateShadowMaps(SceneRenderState& sceneRenderState) {
    if (_context.shadowDetailLevel() == RenderDetailLevel::OFF) {
        return true;
    }

    waitForTasks();
    ShadowMap::clearShadowMapBuffers(_context);
    Time::ScopedTimer timer(_shadowPassTimer);
    // generate shadowmaps for each light
    I32 idx = 0;
    vectorAlg::vecSize count = _sortedShadowCastingLights.size();
    for (vectorAlg::vecSize i = 0; i < count; ++i) {
        Light* light = _sortedShadowCastingLights[i];
        if(light != nullptr) {
            _currentShadowCastingLight = light;
            light->validateOrCreateShadowMaps(_context, sceneRenderState);
            light->generateShadowMaps(idx++ * 6);
        }
    }

    _currentShadowCastingLight = nullptr;
    return true;
}

void LightPool::togglePreviewShadowMaps(GFXDevice& context) {
    _previewShadowMaps = !_previewShadowMaps;
    // Stop if we have shadows disabled
    if (context.shadowDetailLevel() == RenderDetailLevel::OFF || context.getRenderStage().stage() != RenderStage::DISPLAY) {
        ParamHandler::instance().setParam( _ID("rendering.debug.displayShadowDebugInfo"), false);
        _previewShadowMaps = false;
    } else {
        ParamHandler::instance().setParam( _ID("rendering.debug.displayShadowDebugInfo"), _previewShadowMaps);
    }
}

// If we have computed shadowmaps, bind them before rendering any geometry;
void LightPool::bindShadowMaps(GFXDevice& context) {
    // Skip applying shadows if we are rendering to depth map, or we have
    // shadows disabled
    if (context.shadowDetailLevel() == RenderDetailLevel::OFF) {
        return;
    }

    ShadowMap::bindShadowMaps(context);
}

Light* LightPool::getLight(I64 lightGUID, LightType type) {
    Light::LightList::const_iterator it = findLight(lightGUID, type);
    assert(it != std::end(_lights[to_U32(type)]));

    return *it;
}

void LightPool::waitForTasks() {
    for (TaskHandle& task : _lightUpdateTask) {
        task.wait();
    }
    _lightUpdateTask.clear();
}

void LightPool::prepareLightData(const vec3<F32>& eyePos, const mat4<F32>& viewMatrix) {
    waitForTasks();

    // Create and upload light data for current pass
    _activeLightCount.fill(0);
    _sortedLights.resize(0);
    _sortedShadowCastingLights.resize(0);
    _sortedLightProperties.resize(0);
    _sortedShadowProperties.resize(0);

    for (U8 i = 0; i < to_base(LightType::COUNT); ++i) {
        _sortedLights.insert(std::end(_sortedLights), std::begin(_lights[i]), std::end(_lights[i]));
    }

    auto lightUpdate = [this, &eyePos, &viewMatrix](const Task& parentTask) mutable
    {
        std::sort(std::begin(_sortedLights),
                    std::end(_sortedLights),
                    [&eyePos](Light* a, Light* b) -> bool
        {
            return a->getPosition().distanceSquared(eyePos) <
                    b->getPosition().distanceSquared(eyePos);
        });

        U32 totalLightCount = 0;
        vec3<F32> tempColour;
        for (Light* light : _sortedLights) {
            LightType type = static_cast<LightType>(light->getLightType());
            I32 typeIndex = to_I32(type);

            if (!light->getEnabled() || !_lightTypeState[typeIndex]) {
                continue;
            }
            if (totalLightCount >= Config::Lighting::MAX_POSSIBLE_LIGHTS) {
                break;
            }

            _sortedLightProperties.emplace_back();
            LightProperties& temp = _sortedLightProperties.back();
            light->getDiffuseColour(tempColour);
            temp._diffuse.set(tempColour, light->getSpotCosOuterConeAngle());
            // Non directional lights are positioned at specific point in space
            // So we need W = 1 for a valid positional transform
            // Directional lights use position for the light direction. 
            // So we need W = 0 for an infinite distance.
            temp._position.set(viewMatrix.transform(light->getPosition(), type != LightType::DIRECTIONAL), light->getRange());
            // spot direction is not considered a point in space, so W = 0
            temp._direction.set(viewMatrix.transformNonHomogeneous(light->getSpotDirection()), light->getSpotAngle());

            temp._options.x = typeIndex;
            temp._options.y = light->castsShadows();
            if (light->getLightType() == LightType::DIRECTIONAL) {
                temp._options.w = static_cast<DirectionalLight*>(light)->csmSplitCount();
            }
            
           if (light->castsShadows() && _sortedShadowProperties.size() < Config::Lighting::MAX_SHADOW_CASTING_LIGHTS) {
                temp._options.z = to_I32(_sortedShadowProperties.size());
                _sortedShadowProperties.emplace_back(light->getShadowProperties());
                _sortedShadowCastingLights.emplace_back(light);
            }
            ++totalLightCount;
            ++_activeLightCount[typeIndex];
        }
        _buffersUpdated = false;
    };

    // Sort all lights (Sort in parallel by type)
    _lightUpdateTask.emplace_back(CreateTask(Application::instance().kernel().taskPool(), lightUpdate));
    _lightUpdateTask.back().startTask(Task::TaskPriority::LOW, 0);
}

void LightPool::uploadLightData(ShaderBufferLocation lightDataLocation,
                                ShaderBufferLocation shadowDataLocation) {
    waitForTasks();
    uploadLightBuffers();

    _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)]->bind(lightDataLocation);
    _lightShaderBuffer[to_base(ShaderBufferType::SHADOW)]->bind(shadowDataLocation);
}

void LightPool::uploadLightBuffers() {
    if (!_buffersUpdated) {
        // Passing 0 elements is fine (early out in the buffer code)
        vectorAlg::vecSize lightPropertyCount = _sortedLightProperties.size();
        vectorAlg::vecSize lightShadowCount = _sortedShadowProperties.size();

        lightPropertyCount = std::min(lightPropertyCount, static_cast<size_t>(Config::Lighting::MAX_POSSIBLE_LIGHTS));
        lightShadowCount = std::min(lightShadowCount, static_cast<size_t>(Config::Lighting::MAX_SHADOW_CASTING_LIGHTS));

        if (lightPropertyCount > 0) {
            _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)]->updateData(0, lightPropertyCount, _sortedLightProperties.data());
        } else {
            _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)]->setData(nullptr);
        }

        if (lightShadowCount > 0) {
            _lightShaderBuffer[to_base(ShaderBufferType::SHADOW)]->updateData(0, lightShadowCount, _sortedShadowProperties.data());
        } else {
            _lightShaderBuffer[to_base(ShaderBufferType::SHADOW)]->setData(nullptr);
        }
        _buffersUpdated = true;
    }
}

void LightPool::drawLightImpostors(RenderSubPassCmds& subPassesInOut) const {
    if (!_previewShadowMaps) {
        return;
    }

    assert(_lightImpostorShader);
    const U32 directionalLightCount = _activeLightCount[to_base(LightType::DIRECTIONAL)];
    const U32 pointLightCount = _activeLightCount[to_base(LightType::POINT)];
    const U32 spotLightCount = _activeLightCount[to_base(LightType::SPOT)];
    const U32 totalLightCount = directionalLightCount + pointLightCount + spotLightCount;
    if (totalLightCount > 0) {
        PipelineDescriptor pipelineDescriptor;
        pipelineDescriptor._stateHash = _context.getDefaultStateBlock(true);
        pipelineDescriptor._shaderProgram = _lightImpostorShader;

        GenericDrawCommand pointsCmd;
        pointsCmd.primitiveType(PrimitiveType::API_POINTS);
        pointsCmd.drawCount(to_U16(totalLightCount));
        pointsCmd.pipeline(_context.newPipeline(pipelineDescriptor));

        RenderSubPassCmd newSubPass;
        newSubPass._textures.addTexture(TextureData(_lightIconsTexture->getTextureType(),
                                                    _lightIconsTexture->getHandle(),
                                                    to_U8(ShaderProgram::TextureUsage::UNIT0)));

        newSubPass._commands.push_back(pointsCmd);
        subPassesInOut.push_back(newSubPass);
    }
}

};

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

Diff revisions: vs.
Revision Author Commited Message
893 Diff Diff IonutCava picture IonutCava Sun 18 Jun, 2017 17:33:07 +0000

[Ionut]
- Initial implementation of a PipelineStateObject (holds shader program, rasterizer state, etc)
- Rework PCH implementation a bit because VS2017 no longer has a /ZM option

890 Diff Diff IonutCava picture IonutCava Sun 14 May, 2017 20:54:59 +0000

[Ionut]
- Add pre-compiled header support
- Initial code for per-stage tessellation computation

872 Diff Diff IonutCava picture IonutCava Mon 06 Mar, 2017 23:23:20 +0000

[IonutCava]
- Optimise static casts

867 Diff Diff IonutCava picture IonutCava Mon 20 Feb, 2017 17:01:12 +0000

[IonutCava]
- Rename to_XNN and to_const_XNN functions to reflect the target data type they are converting to.
- Cleanup Angle namespace and remove all “inDegrees” parameters from rotation functions. Use aliases to differentiate between Degree and Radian parameters.
- Profile guided optimizations.

854 Diff Diff IonutCava picture IonutCava Wed 08 Feb, 2017 17:14:03 +0000

[IonutCava]
- Texture usage cleanup
- Reflection and Refraction cleanup for CUBE targets: use CUBE_MAP_ARRAY instead of multiple targets

851 Diff Diff IonutCava picture IonutCava Mon 06 Feb, 2017 23:38:14 +0000

[IonutCava]
- Replaced most RenderStage params with RenderStagePass types
- More work on water rendering

847 Diff Diff IonutCava picture IonutCava Sun 05 Feb, 2017 21:16:24 +0000

[IonutCava]
- Code rot fixes:
— Terrain loading (8 bit heightmap only for now)
— Terrain rendering
— Water Plane loading and rendering
— Reflection and Refraction rendering passes (hack for now: need environment cubemaps as separate from reflect/refract maps for planar rendering)
-— ToDo: Separate Reflection / Refraction render targets to Planar R/R and Cube R/R. Environment probes should use Cube Reflections, Water should use planar reflection targets.
- Added a way to register debug views: texture, shader and params. Viewports get automatically scaled and positioned
— ToDo: Add a hover-preview feature
— ToDo: Add a click-lock preview feature

839 Diff Diff IonutCava picture IonutCava Tue 31 Jan, 2017 17:28:13 +0000

[IonutCava]
- Add simplefilewatcher libary: https://github.com/jameswynn/simplefilewatcher
- Use simplefilewatcher to automatically recompile shaders after save without restarting the app!
— Shaders can now be edited on the fly with automatic rebuild if they used one of the modified atoms.

831 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 23:52:34 +0000

[IonutCava]
- More path related updates

830 IonutCava picture IonutCava Wed 25 Jan, 2017 17:29:44 +0000

[IonutCava]
- Add a new Platform element: File
— Move all predefined paths to FileManagement System
- Split MathHelper into MathHelper and StringHelper