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

#include "Scenes/Headers/SceneState.h"
#include "Core/Math/Headers/Transform.h"
#include "Managers/Headers/SceneManager.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Geometry/Shapes/Headers/Object3D.h"
#include "Geometry/Material/Headers/Material.h"
#include "Geometry/Shapes/Headers/SkinnedSubMesh.h"
#include "Environment/Water/Headers/Water.h"
#include "Environment/Terrain/Headers/Terrain.h"
#include "Hardware/Video/Shaders/Headers/ShaderProgram.h"

namespace Divide {


bool SceneRoot::computeBoundingBox(SceneGraphNode* const sgn) {
    BoundingBox& bb = sgn->getBoundingBox();
    bb.reset();
    for (const SceneGraphNode::NodeChildren::value_type& s : sgn->getChildren()) {
        sgn->addBoundingBox(s.second->getBoundingBoxConst(), s.second->getNode()->getType());
    }
    bb.setComputed(true);
    return SceneNode::computeBoundingBox(sgn);
}

SceneGraphNode::SceneGraphNode(SceneGraph* const sg, 
                               SceneNode* const node, 
                               const stringImpl& name ) : GUIDWrapper(),
                                                         _sceneGraph(sg),
                                                         _node(node),
                                                         _elapsedTime(0ULL),
                                                         _parent(nullptr),
                                                         _loaded(true),
                                                         _wasActive(true),
                                                         _active(true),
                                                         _inView(false),
                                                         _selected(false),
                                                         _isSelectable(false),
                                                         _sorted(false),
                                                         _silentDispose(false),
                                                         _boundingBoxDirty(true),
                                                         _shouldDelete(false),
                                                         _updateTimer(GETMSTIME()),
                                                         _childQueue(0),
                                                         _bbAddExclusionList(0),
                                                         _usageContext(NODE_DYNAMIC)
{
    
    assert(_node != nullptr);

    setName( name );
    _instanceID = (node->GetRef() - 1);
    Material* const materialTpl = _node->getMaterialTpl();
    _components[SGNComponent::SGN_COMP_ANIMATION]  = nullptr;
    _components[SGNComponent::SGN_COMP_NAVIGATION] = MemoryManager_NEW NavigationComponent(this);
    _components[SGNComponent::SGN_COMP_PHYSICS]    = MemoryManager_NEW PhysicsComponent(this);
    _components[SGNComponent::SGN_COMP_RENDERING]  = MemoryManager_NEW RenderingComponent(materialTpl != nullptr ? 
                                                                                          materialTpl->clone("_instance_" + name) :
                                                                                          nullptr,
                                                                                          this);
}

/// If we are destroying the current graph node
SceneGraphNode::~SceneGraphNode()
{
    unload();

    PRINT_FN(Locale::get("DELETE_SCENEGRAPH_NODE"), getName().c_str());
    // delete child nodes recursively
    MemoryManager::DELETE_HASHMAP(_children);

    for (SGNComponent*& component : _components) {
        MemoryManager::DELETE( component );
    }
}

void SceneGraphNode::addBoundingBox(const BoundingBox& bb, const SceneNodeType& type) {
    if ( !bitCompare( _bbAddExclusionList, type ) ) {
        _boundingBox.Add( bb );
        if ( _parent ) {
            _parent->getBoundingBox().setComputed( false );
        }
    }
}

SceneGraphNode* SceneGraphNode::getRoot() const {
    return _sceneGraph->getRoot();
}

void SceneGraphNode::getBBoxes(vectorImpl<BoundingBox >& boxes ) const {
    for ( const NodeChildren::value_type& it : _children ) {
        it.second->getBBoxes( boxes );
    }

    boxes.push_back(_boundingBox);
}

///When unloading the current graph node
bool SceneGraphNode::unload(){
    if ( !_loaded ) {
        return true;
    }
    //Unload every sub node recursively
    for ( NodeChildren::value_type& it : _children ) {
        it.second->unload();
    }
    //Some debug output ...
    if ( !_silentDispose && getParent() ) {
        PRINT_FN( Locale::get( "REMOVE_SCENEGRAPH_NODE" ), _node->getName().c_str(), getName().c_str() );
    }

    //if not root
    if ( getParent() ) {
        RemoveResource( _node );
    }

    _loaded = false;

    for ( DELEGATE_CBK<>& cbk : _deletionCallbacks ) {
        cbk();
    }
    return true;
}

///Change current SceneGraphNode's parent
void SceneGraphNode::setParent(SceneGraphNode* const parent) {
    DIVIDE_ASSERT(parent != nullptr, "SceneGraphNode error: Can't add a new node to a null parent. Top level allowed is ROOT");
    assert(parent->getGUID() != getGUID());

    if ( _parent ) {
        if ( *_parent == *parent ) {
            return;
        }
        //Remove us from the old parent's children map
        NodeChildren::iterator it = _parent->getChildren().find( getName() );
        if ( it != _parent->getChildren().end() ) {
            _parent->getChildren().erase( it );
        }
    }
    //Set the parent pointer to the new parent
    _parent = parent;
    //Add ourselves in the new parent's children map
    //Time to add it to the children map
    hashAlg::pair<hashMapImpl<stringImpl, SceneGraphNode*>::iterator, bool > result;
    //Try and add it to the map
    result = hashAlg::insert(_parent->getChildren(), hashAlg::makePair(getName(), this));
    //If we had a collision (same name?)
    if ( !result.second ) {
        ///delete the old SceneGraphNode and add this one instead
        MemoryManager::SAFE_UPDATE( ( result.first )->second, this );
    }
    //That's it. Parent Transforms will be updated in the next render pass;
}

SceneGraphNode* SceneGraphNode::addNode( SceneNode* const node, const stringImpl& name ) {
    STUBBED( "SceneGraphNode: This add/create node system is an ugly HACK so it should probably be removed soon! -Ionut" )

    if ( node->hasSGNParent() ) {
        node->AddRef();
    }
    return createNode( node, name );
}

///Add a new SceneGraphNode to the current node's child list based on a SceneNode
SceneGraphNode* SceneGraphNode::createNode( SceneNode* const node, const stringImpl& name ) {
    //assert(node != nullptr && FindResourceImpl<Resource>(node->getName()) != nullptr);
    //Create a new SceneGraphNode with the SceneNode's info
    //We need to name the new SceneGraphNode
    //If we did not supply a custom name use the SceneNode's name
    SceneGraphNode* sceneGraphNode = MemoryManager_NEW SceneGraphNode(_sceneGraph, 
                                                                      node, 
                                                                      name.empty() ? node->getName() : 
                                                                                     name);
    //Set the current node as the new node's parent
    sceneGraphNode->setParent(this);
    //Do all the post load operations on the SceneNode
    //Pass a reference to the newly created SceneGraphNode in case we need transforms or bounding boxes
    node->postLoad(sceneGraphNode);
    //return the newly created node
    return sceneGraphNode;
}

//Remove a child node from this Node
void SceneGraphNode::removeNode(SceneGraphNode* node) {
    //find the node in the children map
    NodeChildren::iterator it = _children.find(node->getName());
    //If we found the node we are looking for
    if ( it != _children.end() ) {
        //Remove it from the map
        _children.erase( it );
    } else {
        for ( U8 i = 0; i < _children.size(); ++i ) {
            removeNode( node );
        }
    }
    //Beware. Removing a node, does no unload it!
    //Call delete on the SceneGraphNode's pointer to do that
}

//Finding a node based on the name of the SceneGraphNode or the SceneNode it holds
//Switching is done by setting sceneNodeName to false if we pass a SceneGraphNode name
//or to true if we search by a SceneNode's name
SceneGraphNode* SceneGraphNode::findNode(const stringImpl& name, bool sceneNodeName){
    //Null return value as default
    SceneGraphNode* returnValue = nullptr;
     //Make sure a name exists
    if ( !name.empty() ) {
        //check if it is the name we are looking for
        if ( ( sceneNodeName && _node->getName().compare( name ) == 0 ) || getName().compare( name ) == 0 ) {
            // We got the node!
            return this;
        }

        //The current node isn't the one we want, so recursively check all children
        for (const NodeChildren::value_type& it : _children ) {
            returnValue = it.second->findNode( name );
            // if it is not nullptr it is the node we are looking for so just pass it through
            if ( returnValue != nullptr ) {
                return returnValue;
            }
        }
    }

    // no children's name matches or there are no more children
    // so return nullptr, indicating that the node was not found yet
    return nullptr;
}

void SceneGraphNode::Intersect(const Ray& ray, F32 start, F32 end, vectorImpl<SceneGraphNode* >& selectionHits){

    if ( isSelectable() && _boundingBox.Intersect( ray, start, end ) ) {
        selectionHits.push_back( this );
    }

    for (const NodeChildren::value_type& it : _children ) {
        it.second->Intersect( ray, start, end, selectionHits );
    }
}



void SceneGraphNode::setSelected(const bool state) {
    _selected = state;
    for (NodeChildren::value_type& it : _children) {
        it.second->setSelected(_selected);
    }
}

bool SceneGraphNode::updateBoundingBoxTransform(const mat4<F32>& transform){
    if (_boundingBox.Transform(_initialBoundingBox, transform, !_initialBoundingBox.Compare(_initialBoundingBoxCache))) {
        _initialBoundingBoxCache = _initialBoundingBox;
        _boundingSphere.fromBoundingBox(_boundingBox);
        return true;
    }

    return false;
}

void SceneGraphNode::setInitialBoundingBox(const BoundingBox& initialBoundingBox){
    if (!initialBoundingBox.Compare(getInitialBoundingBox())){
        _initialBoundingBox = initialBoundingBox;
        _initialBoundingBox.setComputed(true);
        _boundingBoxDirty = true;
    }
}

void SceneGraphNode::onCameraChange() {
    for (NodeChildren::value_type& it : _children) {
        it.second->onCameraChange();
    }
    _node->onCameraChange(this);
}

///Please call in MAIN THREAD! Nothing is thread safe here (for now) -Ionut
void SceneGraphNode::sceneUpdate(const U64 deltaTime, SceneState& sceneState) {
    //Compute from leaf to root to ensure proper calculations
    for (NodeChildren::value_type& it : _children) {
        assert(it.second);
        it.second->sceneUpdate(deltaTime, sceneState);
    }
    // update local time
    _elapsedTime += deltaTime;
    // update all of the internal components (animation, physics, etc)
    for (U8 i = 0; i < SGNComponent::ComponentType_PLACEHOLDER; ++i) {
        if (_components[i]) {
            _components[i]->update(deltaTime);
        }
    }

    if (getComponent<PhysicsComponent>()->transformUpdated()) {
        _boundingBoxDirty = true;
        for (NodeChildren::value_type& it : _children) {
            it.second->getComponent<PhysicsComponent>()->transformUpdated(true);
        }
    }
    assert(_node->getState() == RES_LOADED);
    //Update order is very important! e.g. Mesh BB is composed of SubMesh BB's.

    //Compute the BoundingBox if it isn't already
    if (!_boundingBox.isComputed()) {
        _node->computeBoundingBox(this);
        assert(_boundingBox.isComputed());
        _boundingBoxDirty = true;
    }

    if (_boundingBoxDirty) {
        if (updateBoundingBoxTransform(getComponent<PhysicsComponent>()->getWorldMatrix())) {
            if (_parent) {
                _parent->getBoundingBox().setComputed(false);
            }
        }
        _boundingBoxDirty = false;
    }

    getComponent<PhysicsComponent>()->transformUpdated(false);

    _node->sceneUpdate(deltaTime, this, sceneState);

    if (_shouldDelete) {
        GET_ACTIVE_SCENEGRAPH()->addToDeletionQueue(this);
    }
}

bool SceneGraphNode::prepareDraw(const SceneRenderState& sceneRenderState, const RenderStage& renderStage){
    if (_reset[renderStage]) {
        _reset[renderStage] = false;
        if (getParent() && !GFX_DEVICE.isCurrentRenderStage(DEPTH_STAGE)) {
            for (SceneGraphNode::NodeChildren::value_type& it : getParent()->getChildren()) {
                if (it.second->getComponent<AnimationComponent>()) {
                    it.second->getComponent<AnimationComponent>()->resetTimers();
                }
            }
        }
    }

    for (U8 i = 0; i < SGNComponent::ComponentType_PLACEHOLDER; ++i) {
        if (_components[i]) {
            if (!_components[i]->onDraw(renderStage)) {
                return false;
            }
        }
    }

    return true;
}

void SceneGraphNode::inView(const bool state){
    _inView = state;
    if (state && getComponent<RenderingComponent>()) {
        getComponent<RenderingComponent>()->inViewCallback();
    }
}

};

Commits for Divide-Framework/trunk/Source Code/Graphs/SceneGraphNode.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)

330 Diff Diff IonutCava picture IonutCava Fri 10 Oct, 2014 17:19:11 +0000

[Ionut]
- New rendering algorithm :
— Perform second pass for visible nodes gathering all render commands and uploading them to an indirect draw buffer
— Render geometry with indirect draw commands
— Removed per-node range binding of the node buffer. Instead, bind the entire buffer once and index data in shaders
— Use “baseInstance” parameter from IndirectDrawCommand as a node buffer index
— Prefer DSA extensions for updating buffer data where applicable
- Moved all rendering specific code from SceneGraphNode to a new RenderingComponent
- Optimized “toString” utility function

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)

328 Diff Diff IonutCava picture IonutCava Sat 04 Oct, 2014 18:03:36 +0000

[Ionut]
- Added per SceneGraphNode material instances. (Cloned from the SceneNode’s material)
- Improved shader loading for materials

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)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

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)

320 IonutCava picture IonutCava Sun 31 Aug, 2014 21:45:33 +0000

[Ionut]
- More AI work (entity captures flag and returns it to base)