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

#include "Core/Headers/ParamHandler.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Rendering/Lighting/ShadowMapping/Headers/ShadowMap.h"
#include "Hardware/Video/Buffers/Framebuffer/Headers/Framebuffer.h"
#include "Hardware/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.h"

ProfileTimer* s_shadowPassTimer = nullptr;

LightManager::LightManager() : FrameListener(),
                               _shadowMapsEnabled(true),
                               _previewShadowMaps(false),
                               _currentShadowPass(0)
{
    s_shadowPassTimer = ADD_TIMER("ShadowPassTimer");
    
    _lightShaderBuffer[SHADER_BUFFER_NORMAL]   = GFX_DEVICE.newSB();
    _lightShaderBuffer[SHADER_BUFFER_SHADOW]   = GFX_DEVICE.newSB();
    
    for(U8 i = 0; i < Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE; ++i){
        normShadowLocation[i] = 255;
        cubeShadowLocation[i] = 255;
        arrayShadowLocation[i] = 255;
    }

    _opaqueGrid = New LightGrid();
    _transparentGrid = New LightGrid();
}

LightManager::~LightManager()
{
    clear();
    REMOVE_TIMER(s_shadowPassTimer);
    SAFE_DELETE(_lightShaderBuffer[SHADER_BUFFER_NORMAL] );
    SAFE_DELETE(_lightShaderBuffer[SHADER_BUFFER_SHADOW]);
    SAFE_DELETE(_opaqueGrid);
    SAFE_DELETE(_transparentGrid);
}

void LightManager::init(){
    STUBBED("Replace light map bind slots with bindless textures! Max texture units is currently hard coded! -Ionut!");

    REGISTER_FRAME_LISTENER(&(this->getInstance()), 2);
    GFX_DEVICE.add2DRenderFunction(DELEGATE_BIND(&LightManager::previewShadowMaps, this, nullptr), 1);
    _lightShaderBuffer[SHADER_BUFFER_NORMAL]->Create(Config::Lighting::MAX_LIGHTS_PER_SCENE, sizeof(LightProperties));
    _lightShaderBuffer[SHADER_BUFFER_NORMAL]->Bind(Divide::SHADER_BUFFER_LIGHT_NORMAL);

    _lightShaderBuffer[SHADER_BUFFER_SHADOW]->Create(Config::Lighting::MAX_LIGHTS_PER_SCENE, sizeof(LightShadowProperties));
    _lightShaderBuffer[SHADER_BUFFER_SHADOW]->Bind(Divide::SHADER_BUFFER_LIGHT_SHADOW);

    _cachedResolution.set(GFX_DEVICE.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)->getResolution());

    U32 maxTextureStorage = GFX_DEVICE.getMaxTextureSlots();
    U32 maxSlotsPerLight = 3;
    maxTextureStorage -= Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE * maxSlotsPerLight;

    for (U8 i = 0; i < Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE; ++i){
        normShadowLocation[i]  = maxTextureStorage + 0 + (i * maxSlotsPerLight);
        cubeShadowLocation[i]  = maxTextureStorage + 1 + (i * maxSlotsPerLight);
        arrayShadowLocation[i] = maxTextureStorage + 2 + (i * maxSlotsPerLight);
    }
}

bool LightManager::clear(){
    //Lights are removed by the sceneGraph
    FOR_EACH(Light::LightMap::value_type it, _lights){
        //in case we had some light hanging
        RemoveResource(it.second);
    }

    _lights.clear();

    return _lights.empty();
}

bool LightManager::addLight(Light* const light){
    light->addShadowMapInfo(New ShadowMapInfo(light));

    if(_lights.find(light->getGUID()) != _lights.end()){
        ERROR_FN(Locale::get("ERROR_LIGHT_MANAGER_DUPLICATE"), light->getGUID());
        return false;
    }

    light->setSlot((U8)_lights.size());
    _lights.insert(std::make_pair(light->getGUID(), light));
    GET_ACTIVE_SCENE()->renderState().getCameraMgr().addNewCamera(light->getName(), light->shadowCamera());
    return true;
}

// try to remove any leftover lights
bool LightManager::removeLight(U32 lightId){
    /// we can't remove a light if the light list is empty. That light has to exist somewhere!
    assert(!_lights.empty());

    Light::LightMap::const_iterator it = _lights.find(lightId);

    if(it == _lights.end()){
        ERROR_FN(Locale::get("ERROR_LIGHT_MANAGER_REMOVE_LIGHT"),lightId);
        return false;
    }

    _lights.erase(it); //remove it from the map
    return true;
}

void LightManager::idle(){
    _shadowMapsEnabled = ParamHandler::getInstance().getParam<bool>("rendering.enableShadows");

    s_shadowPassTimer->pause(!_shadowMapsEnabled);
}

void LightManager::updateResolution(I32 newWidth, I32 newHeight){
    FOR_EACH(Light::LightMap::value_type& it, _lights)
        it.second->updateResolution(newWidth, newHeight);

    _cachedResolution.set(newWidth, newHeight);
}

///Check light properties for every light (this is bound to the camera change listener group
///Update only if needed. Get projection and view matrices if they changed
///Also, search for the dominant light if any
void LightManager::onCameraChange(){
     FOR_EACH(Light::LightMap::value_type& it, _lights){
        assert(it.second != nullptr);
        it.second->onCameraChange();
    }
}

bool LightManager::buildLightGrid(const mat4<F32>& viewMatrix, const mat4<F32>& projectionMatrix, const vec2<F32>& zPlanes){
    vectorImpl<LightGrid::LightInternal > omniLights;
    omniLights.reserve(_lights.size());
    FOR_EACH(Light::LightMap::value_type& it, _lights){
        const Light& light = *it.second;
        if (light.getLightType() == LIGHT_TYPE_POINT){
            omniLights.push_back(LightGrid::make_light(light.getPosition(), light.getDiffuseColor(), light.getRange()));
        }
    }
    if (!omniLights.empty()){
        _transparentGrid->build(vec2<U16>(Config::Lighting::LIGHT_GRID_TILE_DIM_X, Config::Lighting::LIGHT_GRID_TILE_DIM_Y),
                                _cachedResolution,
                                omniLights,
                                viewMatrix,
                                projectionMatrix,
                                zPlanes.x, 
                                vectorImpl<vec2<F32> >());

        {
            vectorImpl<vec2<F32> > depthRanges;
            GFX_DEVICE.DownSampleDepthBuffer(depthRanges);
            // We take a copy of this, and prune the grid using depth ranges found from pre-z pass (for opaque geometry).
            // Note that the pruning does not occur if the pre-z pass was not performed (depthRanges is empty in this case).
            _opaqueGrid = _transparentGrid;
            _opaqueGrid->prune(depthRanges);
            _transparentGrid->pruneFarOnly(zPlanes.x, depthRanges);
        }
    }

    return true;
}

/// 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 LightManager::framePreRenderEnded(const FrameEvent& evt){
    if(!_shadowMapsEnabled)
        return true;

    START_TIMER(s_shadowPassTimer);

    //Tell the engine that we are drawing to depth maps
    //set the current render stage to SHADOW_STAGE
    RenderStage previousRS = GFX_DEVICE.setRenderStage(SHADOW_STAGE);
    //generate shadowmaps for each light
    FOR_EACH(Light::LightMap::value_type& light, _lights){
        setCurrentLight(light.second);
        light.second->generateShadowMaps(GET_ACTIVE_SCENE()->renderState());
    }

    //Revert back to the previous stage
    GFX_DEVICE.setRenderStage(previousRS);

    STOP_TIMER(s_shadowPassTimer);

    return true;
}

void LightManager::togglePreviewShadowMaps() { 
    _previewShadowMaps = !_previewShadowMaps; 
    //Stop if we have shadows disabled
    if (!_shadowMapsEnabled || !GFX_DEVICE.isCurrentRenderStage(DISPLAY_STAGE))
        return;

    FOR_EACH(Light::LightMap::value_type& it, _lights){
        if(it.second->getShadowMapInfo()->getShadowMap()){
            it.second->getShadowMapInfo()->getShadowMap()->togglePreviewShadowMaps(_previewShadowMaps);
        }
    }
}

void LightManager::previewShadowMaps(Light* light) {
    //Stop if we have shadows disabled
    if (!_shadowMapsEnabled || !_previewShadowMaps || !GFX_DEVICE.isCurrentRenderStage(DISPLAY_STAGE))
        return;

    if (!light) light = _lights.begin()->second;

    if(!light->castsShadows())
        return;

    light->getShadowMapInfo()->getShadowMap()->previewShadowMaps();
}

//If we have computed shadowmaps, bind them before rendering any geometry;
void LightManager::bindDepthMaps(){
    //Skip applying shadows if we are rendering to depth map, or we have shadows disabled
    if(!_shadowMapsEnabled)
        return;

    for(U8 i = 0; i < std::min((U32)_lights.size(), Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE); ++i){
        Light* lightLocal = getLight(i);
        assert(lightLocal);

        if(!lightLocal->castsShadows())
            continue;

        ShadowMap* sm = lightLocal->getShadowMapInfo()->getShadowMap();
        if(sm){
#           if defined(_DEBUG)
                U8 slot = getShadowBindSlot(lightLocal->getLightType(), i);
                assert(slot < GFX_DEVICE.getMaxTextureSlots());
                sm->Bind(slot);
#           else
                sm->Bind(getShadowBindSlot(lightLocal->getLightType(), i));
#           endif
        }
    }
}

bool LightManager::shadowMappingEnabled() const {
    if(!_shadowMapsEnabled)
        return false;

    FOR_EACH(Light::LightMap::value_type light, _lights){
        if(!light.second->castsShadows())
            continue;

        ShadowMapInfo* smi = light.second->getShadowMapInfo();
        //no shadow info;
        if(!smi)
            continue;

        ShadowMap* sm = smi->getShadowMap();
        //no shadow map;
        if(!sm)
            continue;

        if(sm->getDepthMap())
            return true;
    }

    return false;
}

Light* LightManager::getLight(U32 slot) {
    Light::LightMap::const_iterator it = std::find_if(_lights.begin(), _lights.end(), [&slot](const Light::LightMap::value_type& vt) 
                                                                                       { return vt.second->getSlot() == slot; });
    assert(it != _lights.end());
    return it->second;
}

void LightManager::updateAndUploadLightData(const mat4<F32>& viewMatrix){
    _lightProperties.resize(0);
    _lightProperties.reserve(_lights.size());

    _lightShadowProperties.resize(0);
    _lightShadowProperties.reserve(_lights.size());

    FOR_EACH(Light::LightMap::value_type& lightIt, _lights){
        Light* light = lightIt.second;
        if (light->_dirty[Light::PROPERTY_TYPE_PHYSICAL]){
            LightProperties temp = light->getProperties();
            if (light->getLightType() == LIGHT_TYPE_DIRECTIONAL){
                temp._position.set(vec3<F32>(viewMatrix * temp._position), temp._position.w);
            }else if (light->getLightType() == LIGHT_TYPE_SPOT){
                temp._direction.set(vec3<F32>(viewMatrix * temp._direction), temp._direction.w);
            }
            _lightProperties.push_back(temp);
        }else{
            _lightProperties.push_back(light->getProperties());
        }
        if(light->castsShadows()){
            _lightShadowProperties.push_back(light->getShadowProperties());
            light->_dirty[Light::PROPERTY_TYPE_SHADOW] = false;
        }

        light->_dirty[Light::PROPERTY_TYPE_VISUAL] = false;
        light->_dirty[Light::PROPERTY_TYPE_PHYSICAL] = false;        
    }

    if(!_lightProperties.empty())
        _lightShaderBuffer[SHADER_BUFFER_NORMAL]->UpdateData(0, _lightProperties.size() * sizeof(LightProperties), (void*)&_lightProperties.front(), true);
    if(!_lightShadowProperties.empty())
        _lightShaderBuffer[SHADER_BUFFER_SHADOW]->UpdateData(0, _lightShadowProperties.size() * sizeof(LightShadowProperties), (void*)&_lightShadowProperties.front(), true);
}

Commits for Divide-Framework/trunk/Source Code/Managers/LightManager.cpp

Diff revisions: vs.
Revision Author Commited Message
286 Diff Diff IonutCava picture IonutCava Fri 18 Jul, 2014 16:32:03 +0000

[Ionut] [[BR]]

    • very buggy commit ** [[BR]]

- New rendering pipeline: [[BR]]
— Bumped OpenGL version to 4.4 [[BR]]
— Command based rendering. GFXDevice dispatches rendering commands to their respective buffers [[BR]]
— State changing is exclusively controlled by the GFXDevice class [[BR]]
— Material properties and transform matrices are stored in shader storage buffers that are updated after culling and uploaded once per RenderPass. Objects use drawIDs to index data in shaders [[BR]]
— Removed all custom matrices and other, per shader, bind data [[BR]]
— Removed per node light data. Light culling and shader buffers will replace the old light management system [[BR]]
— Framebuffers now use the Texture class for attachments [[BR]]
— Sampler objects now work like RenderStateBlocks. GL_API handles them and stores them in a hash indexed map [[BR]]
— Removed “prepareMaterial” calls. Pre-draw material setup is now only limited to texture binding [[BR]]
— Moved immediate mode emulation and primitive rendering from API level to GFXDevice level [[BR]]
— Framebuffer rendering must be completed with a call to end() to ensure proper MSAA resolve (asserts, otherwise) [[BR]]
- Fixed hash code generation for RenderStateBlock (and now, glSamplerObject) using boost::hash_combine [[BR]]
- Temporarily disabled XML caching for materials [[BR]]

285 Diff Diff IonutCava picture IonutCava Wed 02 Jul, 2014 18:33:25 +0000

[Ionut][[BR]]
- Per SGN shader data implementation part 1.75 / 2 [[BR]]
— Upload node data into a SSBO in one single call [[BR]]
- Re-factored LightManager to upload light info and shadow info in single upload calls [[BR]]
- Improved GUIConsole load performance by using a boost::circular_buffer for initial messages [[BR]]

284 Diff Diff IonutCava picture IonutCava Tue 01 Jul, 2014 20:54:08 +0000

[Ionut][[BR]]
- Per SGN shader data implementation part 1 / 2 [[BR]]
— Gather node info and transforms into custom struct for visible nodes and store them in a GFXDevice local vector [[BR]]
- Removed “prepareDepthMaterial” and added depthPass flag to “prepareMaterial” [[BR]]

274 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 12:56:03 +0000

[Ionut] [[BR]]
- Simplified buffer based rendering (VertexBuffer & GenericVertexData are now exclusively command based) [[BR]]
- Update bone buffer to persistent mapped-SSBO system with double-buffering [[BR]]
- Simplified sky rendering and (finally) reduced the sun’s radius [[BR]]

272 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 11:30:51 +0000

[Ionut] [[BR]]
- Added initial code for Forward+ rendering (grid based light culling) [[BR]]
- Simplified Light class [[BR]]
- Moved more light uniform data to ShaderBuffers [[BR]]
- Double buffered grass rendering [[BR]]
- Added a better attribute interface to GenericVertexData [[BR]]
- Fixed screenshot capture [[BR]]
- Fixed texture double-bind checks [[BR]]

270 Diff Diff IonutCava picture IonutCava Thu 05 Jun, 2014 19:08:07 +0000

[Ionut][[BR]]
- SubMeshes now use a single vertex buffer (owned by the parent mesh) with proper offsetting and querying [[BR]]
— Implementation not optimal yet [[BR]]
- Cleaned up VertexBuffer related classes [[BR]]

268 Diff Diff IonutCava picture IonutCava Wed 04 Jun, 2014 10:20:27 +0000

[IonutCava] [[BR]]
- Terrain and vegetation updates: [[BR]]
— Use standard phong lighting model [[BR]]
— Separate grass patches per chunk [[BR]]
— Reduce number of required texture bind points for terrain by adding both textures and normal maps in a single texture array [[BR]]
— Draw terrain with 2 drawcalls (using glMultiDrawElements twice, once for LoD == 0 and once for LoD > 0) [[BR]]
[[BR]]
- Buffer management updates: [[BR]]
— Unified buffer binding system [[BR]]
— Made Uniform buffer objects visible to all classes and moved lightUBO to LightManager, matricesUBO to GFXDevice etc [[BR]]
— Added initial support for Shader Buffer Objects [[BR]]
— Moved viewport management to GFXDevice class [[BR]]
[[BR]]
- Rendering improvements: [[BR]]
— Added Hi-Z occlusion culling to instanceCull shader (using Hi-Z depth buffer constructed in GFXDevice class) [[BR]]
— Resolved issues with shadow maps overriding texture bind locations [[[BR]]
— Improved shader and shader program loading [[BR]]
— Improved material transparency support [[BR]]
— Added buffer lock manager class from “Approaching Zero Driver Overhead in OpenGL (Presented by NVIDIA)” speech at GDC14 [[BR]]

267 Diff Diff k1ngp1n picture k1ngp1n Wed 28 May, 2014 11:08:12 +0000

[Ionut] [[BR]]
- Improved texture handling: [[BR]]
— No more texture unbind (except when clearing the frame state) [[BR]]
— Moved texture bind checking to the GL_API class [[BR]]
- Fixed a crash related to vegetation loading due to compiler optimizations [[BR]]
- removed all “releaseMaterial” functions as they are no longer needed [[BR]]

264 Diff Diff k1ngp1n picture k1ngp1n Tue 27 May, 2014 13:04:38 +0000

[Ionut] [[BR]]
- New camera system: [[BR]]
— Stack based (push/pop active camera) [[BR]]
— Per camera frustum [[BR]]
— Per camera projection [[BR]]
— Shadow mapping now uses the new camera system (each light has a shadow camera) [[BR]]
[[BR]]
- New terrain, water and vegetation system: [[BR]]
— Direct import of terrain from L3DT both as 8-bit grayscale and 16-bit raw formats [[BR]]
— Multiple alpha maps for texture splatting support [[BR]]
— Per texture detail map support [[BR]]
— Transform feedback based visibility culling for vegetation [[BR]]
— Alpha-map based vegetation placing on terrain [[BR]]
— Water now uses a refraction map instead of alpha blending for better refraction effects [[BR]]
[[BR]]
- SceneGraph improvements: [[BR]]
— Better bounding box updates from child to parent [[BR]]
— Better onDraw / postDraw implementation [[BR]]
[[BR]]
- Performance improvements: [[BR]]
— Batch 2D rendering tasks together as much as possible[[BR]]
— Improve renderStateBlock hash generation for better sorting [[BR]]
— Move most state related gfx changes from API implementation to the GFXDevice class [[BR]]
— Move viewport stack to the GFXDevice class [[BR]]
— Added various performance counters (frame duration with round-robin query system, draw call count, etc) [[BR]]
— Fixed and improved clip plane management [[BR]]
— Delete client-side texture data after GPU upload [[BR]]
[[BR]]
- New features: [[BR]]
— Added callback support to the Task class so that a specific task may call a function in the main thread upon completion [[BR]]
— Added mouse-wheel zoom support to Orbit/ThirdPerson cameras [[BR]]
— Added 2D Texture Array support (e.g. used for terrain textures) [[BR]]

262 k1ngp1n picture k1ngp1n Tue 06 May, 2014 21:04:00 +0000

[Ionut] [[BR]]
- Some AI refactoring (basic AIEntity <-> AESOP interoperability) [[BR]]
- Some render batch sorting code refactored and fixed (wasn’t properly sorted in FINAL_STAGE) [[BR]]
- Simplified RenderStateBlockDescriptor and deferred hash value calculation [[BR]]
- Basic draw call count implementation [[BR]]
- Renamed some classes [[BR]]