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
361
362
363
#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.setMinFilter(TextureFilter::LINEAR);
    iconSampler.setAnisotropy(0);
    iconSampler.setWrapMode(TextureWrap::REPEAT);
    iconSampler.toggleSRGBColourSpace(true);

    TextureDescriptor iconDescriptor(TextureType::TEXTURE_2D);
    iconDescriptor.setSampler(iconSampler);

    ResourceDescriptor iconImage("LightIconTexture");
    iconImage.setThreadedLoading(false);
    iconImage.setResourceLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
    iconImage.setResourceName("lightIcons.png");
    iconImage.setPropertyDescriptor(iconDescriptor);

    _lightIconsTexture = CreateResource<Texture>(_parentScene.resourceCache(), iconImage);

    _init = true;
}

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

    _parentScene.sceneGraph().removeNodesByType(SceneNodeType::TYPE_LIGHT);
    for (Light::LightList& lightList : _lights) {
        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, GFX::CommandBuffer& bufferInOut) {
    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, bufferInOut);
        }
    }

    _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, GFX::CommandBuffer& bufferInOut) {
    // Skip applying shadows if we are rendering to depth map, or we have
    // shadows disabled
    if (context.shadowDetailLevel() == RenderDetailLevel::OFF) {
        return;
    }

    ShadowMap::bindShadowMaps(context, bufferInOut);
}

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(_context.parent().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)]->writeData(0, lightPropertyCount, _sortedLightProperties.data());
        } else {
            _lightShaderBuffer[to_base(ShaderBufferType::NORMAL)]->writeData(nullptr);
        }

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

void LightPool::drawLightImpostors(GFX::CommandBuffer& bufferInOut) 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));

        GFX::BindPipelineCommand bindPipeline;
        bindPipeline._pipeline = _context.newPipeline(pipelineDescriptor);
        GFX::BindPipeline(bufferInOut, bindPipeline);
        
        GFX::BindDescriptorSetsCommand descriptorSetCmd;
        descriptorSetCmd._set._textureData.addTexture(TextureData(_lightIconsTexture->getTextureType(),
                                                                  _lightIconsTexture->getHandle()),
                                                      to_U8(ShaderProgram::TextureUsage::UNIT0));
        GFX::BindDescriptorSets(bufferInOut, descriptorSetCmd);

        GFX::DrawCommand drawCommand;
        drawCommand._drawCommands.push_back(pointsCmd);
        GFX::AddDrawCommands(bufferInOut, drawCommand);
    }
}

};

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

Diff revisions: vs.
Revision Author Commited Message
949 Diff Diff IonutCava picture IonutCava Thu 19 Oct, 2017 21:48:37 +0000

[Ionut]
- More command buffer refactoring

938 Diff Diff IonutCava picture IonutCava Wed 16 Aug, 2017 21:35:55 +0000

[Ionut]
- Separate texture binding slot from TextureData
- Binding slot is now a property of the descriptor set
- Remove bind() calls from texture’s public interface
ToDo
- Add image layer binding options (addTextureLayer(data, binding, layer, ...)

933 Diff Diff IonutCava picture IonutCava Tue 15 Aug, 2017 00:02:05 +0000

[Ionut]
- CommandBuffer Part 2/3: code compiles and splash screen renders and application doesn’t crash (still has drawing issues)

929 Diff Diff IonutCava picture IonutCava Sat 12 Aug, 2017 17:34:44 +0000

[Ionut]
- More work on finishing up new PushConstant / Command buffer rendering system:
— Everything compiles and runs but with graphical and performance issues

909 Diff Diff IonutCava picture IonutCava Thu 29 Jun, 2017 23:57:18 +0000

[Ionut]
- Rework RenderTarget class
— RTAttachment now deal with textures directly
— RT size needs to be specified upfront
- Application class is no longer a Singleton but passed around in the PlatformContext

907 Diff Diff IonutCava picture IonutCava Wed 28 Jun, 2017 23:16:40 +0000

[Ionut]
- Rework texture loading, mip map generation, sampler usage, etc
- ResourceDescriptor for textures now ONLY takes a TextureDescriptor as a property descriptor. Sampler must be assigned to the tex descriptor:
— ToDo: Separate samplers completely from textures and assign them from a pool to textures at bind time

899 Diff Diff IonutCava picture IonutCava Fri 23 Jun, 2017 15:37:44 +0000

[IonutCava]
- Move sRGB conversion and fog calculation to post-processing stages (fog in postProcessing using the depth buffer and sRGB in the presentToScreen step)
- Split the bloom.glsl file into multiple shaders: bloom, tonemap and luminanceCalc for ease of use purposes
- Rework RenderBin sorting: sort translucent/transparent nodes by material in depth passes
- Sort order is no longer part of RenderBin for better control

895 Diff Diff IonutCava picture IonutCava Wed 21 Jun, 2017 21:10:26 +0000

[IonutCava]
- Reorder and cleanup OpenGL backend a bit.
- Small code cleanup
- Some small profile-guided optimizations

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 IonutCava picture IonutCava Sun 14 May, 2017 20:54:59 +0000

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