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
#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"

namespace Divide {

ProfileTimer* s_shadowPassTimer = nullptr;

LightManager::LightManager() : FrameListener(),
                               _init(false),
                               _shadowMapsEnabled(true),
                               _previewShadowMaps(false),
                               _currentShadowPass(0)
{
    // shadowPassTimer is used to measure the CPU-duration of shadow map generation step
    s_shadowPassTimer = ADD_TIMER("ShadowPassTimer");
    // SHADER_BUFFER_NORMAL holds general info about the currently active lights: position, color, etc.
	_lightShaderBuffer[SHADER_BUFFER_NORMAL] = nullptr;
    // SHADER_BUFFER_SHADOWS holds info about the currently active shadow casting lights: 
    // ViewProjection Matrices, View Space Position, etc
	_lightShaderBuffer[SHADER_BUFFER_SHADOW] = nullptr;
    // We bind shadow maps to the last available texture slots that the hardware supports. 
    // Starting offsets for each texture type is stored here
    _cubeShadowLocation  = 255;
    _normShadowLocation  = 255;
    _arrayShadowLocation = 255;
	ParamHandler::getInstance().setParam<bool>("rendering.debug.showSplits", false);
}

LightManager::~LightManager()
{
    clear();
    REMOVE_TIMER(s_shadowPassTimer);
    MemoryManager::DELETE( _lightShaderBuffer[SHADER_BUFFER_NORMAL] );
    MemoryManager::DELETE( _lightShaderBuffer[SHADER_BUFFER_SHADOW] );
}

void LightManager::init(){
	if (_init) {
		return;
	}
    STUBBED("Replace light map bind slots with bindless textures! Max texture units is currently used! -Ionut!");

    REGISTER_FRAME_LISTENER(&(this->getInstance()), 2);

    GFX_DEVICE.add2DRenderFunction(DELEGATE_BIND(&LightManager::previewShadowMaps, this, nullptr), 1);
	// SHADER_BUFFER_NORMAL holds general info about the currently active lights: position, color, etc.
	_lightShaderBuffer[SHADER_BUFFER_NORMAL] = GFX_DEVICE.newSB();
	// SHADER_BUFFER_SHADOWS holds info about the currently active shadow casting lights: 
    // ViewProjection Matrices, View Space Position, etc
	_lightShaderBuffer[SHADER_BUFFER_SHADOW] = GFX_DEVICE.newSB();

    _lightShaderBuffer[SHADER_BUFFER_NORMAL]->Create(Config::Lighting::MAX_LIGHTS_PER_SCENE, sizeof(LightProperties));
    _lightShaderBuffer[SHADER_BUFFER_NORMAL]->Bind(SHADER_BUFFER_LIGHT_NORMAL);

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

    _cachedResolution.set(GFX_DEVICE.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)->getResolution());
    _init = true;
}

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

    UNREGISTER_FRAME_LISTENER(&(this->getInstance()));

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

    _lights.clear();

    _init = false;

    return _lights.empty();
}

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

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

    hashAlg::emplace(_lights, light->getGUID(), light);
    GET_ACTIVE_SCENE()->renderState().getCameraMgr().addNewCamera(light->getName(), light->shadowCamera());
    return true;
}

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

	Light::LightMap::iterator it = _lights.find(lightGUID);

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

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

void LightManager::idle(){
    _shadowMapsEnabled = ParamHandler::getInstance().getParam<bool>("rendering.enableShadows");
	_shadowMapsEnabled = false;
    s_shadowPassTimer->pause(!_shadowMapsEnabled);
}

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

    _cachedResolution.set(newWidth, newHeight);
}

U8 LightManager::getShadowBindSlotOffset(ShadowSlotType type) {
    if (_cubeShadowLocation == _normShadowLocation && _normShadowLocation == _arrayShadowLocation && _arrayShadowLocation == 255) {
        U32 maxTextureStorage = ParamHandler::getInstance().getParam<I32>( "rendering.maxTextureSlots", 16 );
        _cubeShadowLocation  = maxTextureStorage - ( Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE * 3 );
        _normShadowLocation  = maxTextureStorage - ( Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE * 2 );
        _arrayShadowLocation = maxTextureStorage - ( Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE * 1 );
    }
    switch (type){
        default:
        case SHADOW_SLOT_TYPE_NORMAL: return _normShadowLocation;
        case SHADOW_SLOT_TYPE_CUBE  : return _cubeShadowLocation;
        case SHADOW_SLOT_TYPE_ARRAY : return _arrayShadowLocation;
    };
}


///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 (Light::LightMap::value_type& it : _lights) {
        it.second->onCameraChange();
    }
}

/// 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 (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 (Light::LightMap::value_type& it : _lights) {
        if ( it.second->getShadowMapInfo()->getShadowMap() ) {
            it.second->getShadowMapInfo()->getShadowMap()->togglePreviewShadowMaps( _previewShadowMaps );
        }
    }
}

void LightManager::previewShadowMaps(Light* light) {
#   ifdef _DEBUG
        //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;
        }
        if ( light->getShadowMapInfo()->getShadowMap() ) {
            light->getShadowMapInfo()->getShadowMap()->previewShadowMaps();
        }
#   endif
}

//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 ) {
            sm->Bind( getShadowBindSlotOffset( lightLocal->getLightType() ) + i );
        }
    }
}

bool LightManager::shadowMappingEnabled() const {
	if (!_shadowMapsEnabled){
		return false;
	}
	for (const 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(I64 lightGUID) {
	Light::LightMap::const_iterator it = std::find_if(_lights.begin(), _lights.end(),
                                                      [&lightGUID](const Light::LightMap::value_type vt)->bool {
													    return vt.second->getGUID() == lightGUID; 
													  });
    assert(it != _lights.end());
    return it->second;
}

void LightManager::updateAndUploadLightData( const mat4<F32>& viewMatrix ) {
    _lightProperties.clear();
    _lightProperties.reserve(static_cast<vectorAlg::vecSize>(_lights.size()));

    _lightShadowProperties.clear();
    _lightShadowProperties.reserve(static_cast<vectorAlg::vecSize>(_lights.size()));

	for (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 * vec4<F32>(temp._position.xyz(), 0.0f) ), temp._position.w );
            } else if ( light->getLightType() == LIGHT_TYPE_SPOT ) {
                temp._direction.set(vec3<F32>(viewMatrix * vec4<F32>(temp._direction.xyz(), 0.0f) ), 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 ),
                                                             _lightProperties.data(),
                                                             true );
    }
    if ( !_lightShadowProperties.empty() ) {
        _lightShaderBuffer[SHADER_BUFFER_SHADOW]->UpdateData(0, 
                                                             _lightShadowProperties.size() * sizeof( LightShadowProperties ),
                                                             _lightShadowProperties.data(),
                                                             true );
    }
}

};

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

Diff revisions: vs.
Revision Author Commited Message
331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

329 Diff Diff IonutCava picture IonutCava Tue 07 Oct, 2014 12:51:37 +0000

[Ionut]
- Modified material class and shaders to support multiple BRDFs (currently, only Flat, Phong and Blinn-Phong supported with Cook-Torrance and Oren-Nayar in future commits)
- Optimized transform updates and queries
- Fixed an indirect draw command (no buffer was bound to GL_DRAW_INDIRECT_BUFFER, violating a core requirement)

326 Diff Diff IonutCava picture IonutCava Tue 30 Sep, 2014 21:11:32 +0000

[Ionut]
- Fixed more memory leaks
- Simplified Task interface and timing System
- Improved compatibility between Boost, STL and EASTL with random combinations of vectors, strings and maps
- Simplified Light class by removing the “slot” member
- Random optimizations

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

323 Diff Diff IonutCava picture IonutCava Thu 11 Sep, 2014 20:58:50 +0000

[Ionut]
- Reworked GFXDevice API initialization system
- Added a separate map for boolean values in ParamHandler
- More cleanups in GFXDevice class
- Fixed an infinite loop issue in Task class

322 Diff Diff IonutCava picture IonutCava Sat 06 Sep, 2014 20:33:47 +0000

[Ionut]
- Refactored most of Boost related code to be C++11 based
— Boost is only used for ThreadPool, Mutex handling, XML parsing and networking (ASIO)
— Function binds, threads, regex, NonCopyable base, Hashing algorithms and more are now using C++11 libraries
- Replaced all FOR_EACH calls with standard, range, “for” calls

321 Diff Diff IonutCava picture IonutCava Wed 03 Sep, 2014 22:05:15 +0000

[Ionut]
- Added support (and enabled by default) for the EASTL library (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / https://github.com/paulhodge/EASTL)
— Strings, vectors and hash_maps can be combined from EASTL, STL and Boost (not all combinations work. e.g. EASTL strings with STL/Boost containers due to the lack of a proper hash function)

319 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 21:37:57 +0000

[Ionut]
- Performance tweaks based on profiling data

318 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)

302 IonutCava picture IonutCava Wed 06 Aug, 2014 22:09:55 +0000

[Ionut]
- GenericVertexData buffer size (for read/write buffering) is now configurable instead of a fixed 3x and also applies to non-persistently mapped buffers
- Moved OpenGL enum tables to Divide::GLUtil::GL_ENUM_TABLE
- More code cleanups (glResources, glError, glVertexArray, glGenericVertexData, glIMPrimitive)