Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Identifier.h @ 7286

Last change on this file since 7286 was 7284, checked in by landauf, 14 years ago

merged consolecommands3 branch back to trunk.

note: the console command interface has changed completely, but the documentation is not yet up to date. just copy an existing command and change it to your needs, it's pretty self-explanatory. also the include files related to console commands are now located in core/command/. in the game it should work exactly like before, except for some changes in the auto-completion.

  • Property svn:eol-style set to native
File size: 24.8 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30    @file
31    @brief Definition of the Identifier class, definition and implementation of the ClassIdentifier class.
32
33    The Identifier contains all needed information about the class it belongs to:
34     - the name
35     - a list with all objects
36     - parents and children
37     - the factory (if available)
38     - the networkID that can be synchronised with the server
39     - all configurable variables (if available)
40
41    Every object has a pointer to the Identifier of its class. This allows the use isA(...),
42    isExactlyA(...), isChildOf(...) and isParentOf(...).
43
44    To create the class-hierarchy, the Identifier has some intern functions and variables.
45
46    Every Identifier is in fact a ClassIdentifier, but they are derived from Identifier.
47*/
48
49#ifndef _Identifier_H__
50#define _Identifier_H__
51
52#include "CorePrereqs.h"
53
54#include <cassert>
55#include <map>
56#include <set>
57#include <string>
58#include <typeinfo>
59#include <loki/TypeTraits.h>
60
61#include "util/Debug.h"
62#include "MetaObjectList.h"
63#include "ObjectList.h"
64#include "ObjectListBase.h"
65#include "Super.h"
66
67namespace orxonox
68{
69    // ###############################
70    // ###       Identifier        ###
71    // ###############################
72    //! The Identifier is used to identify the class of an object and to store information about the class.
73    /**
74        The Identifier contains all needed information about the class it belongs to:
75         - the name
76         - a list with all objects
77         - parents and children
78         - the factory (if available)
79         - the networkID that can be synchronised with the server
80         - all configurable variables (if available)
81
82        Every object has a pointer to the Identifier of its class. This allows the use isA(...),
83        isExactlyA(...), isChildOf(...) and isParentOf(...).
84
85        You can't directly create an Identifier, it's just the base-class for ClassIdentifier.
86    */
87    class _CoreExport Identifier
88    {
89        public:
90            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
91            inline const std::string& getName() const { return this->name_; }
92            void setName(const std::string& name);
93
94            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
95            inline const uint32_t getNetworkID() const { return this->networkID_; }
96            void setNetworkID(uint32_t id);
97
98            /** @brief Returns the unique ID of the class */
99            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
100
101            /** @brief Returns the list of all existing objects of this class. @return The list */
102            inline ObjectListBase* getObjects() const { return this->objects_; }
103
104            /** @brief Sets the Factory. @param factory The factory to assign */
105            inline void addFactory(Factory* factory) { this->factory_ = factory; }
106            /** @brief Returns true if the Identifier has a Factory. */
107            inline bool hasFactory() const { return (this->factory_ != 0); }
108
109            BaseObject* fabricate(BaseObject* creator);
110
111            /** @brief Returns true if the class can be loaded through XML. */
112            inline bool isLoadable() const { return this->bLoadable_; }
113            /** @brief Set the class to be loadable through XML or not. */
114            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
115
116            bool isA(const Identifier* identifier) const;
117            bool isExactlyA(const Identifier* identifier) const;
118            bool isChildOf(const Identifier* identifier) const;
119            bool isDirectChildOf(const Identifier* identifier) const;
120            bool isParentOf(const Identifier* identifier) const;
121            bool isDirectParentOf(const Identifier* identifier) const;
122
123
124            /////////////////////////////
125            ////// Class Hierarchy //////
126            /////////////////////////////
127            static void createClassHierarchy();
128
129            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
130            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
131
132            /** @brief Returns the parents of the class the Identifier belongs to. @return The list of all parents */
133            inline const std::set<const Identifier*>& getParents() const { return this->parents_; }
134            /** @brief Returns the begin-iterator of the parents-list. @return The begin-iterator */
135            inline std::set<const Identifier*>::const_iterator getParentsBegin() const { return this->parents_.begin(); }
136            /** @brief Returns the end-iterator of the parents-list. @return The end-iterator */
137            inline std::set<const Identifier*>::const_iterator getParentsEnd() const { return this->parents_.end(); }
138
139            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
140            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
141            /** @brief Returns the begin-iterator of the children-list. @return The begin-iterator */
142            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
143            /** @brief Returns the end-iterator of the children-list. @return The end-iterator */
144            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
145
146            /** @brief Returns the direct parents of the class the Identifier belongs to. @return The list of all direct parents */
147            inline const std::set<const Identifier*>& getDirectParents() const { return this->directParents_; }
148            /** @brief Returns the begin-iterator of the direct-parents-list. @return The begin-iterator */
149            inline std::set<const Identifier*>::const_iterator getDirectParentsBegin() const { return this->directParents_.begin(); }
150            /** @brief Returns the end-iterator of the direct-parents-list. @return The end-iterator */
151            inline std::set<const Identifier*>::const_iterator getDirectParentsEnd() const { return this->directParents_.end(); }
152
153            /** @brief Returns the direct children the class the Identifier belongs to. @return The list of all direct children */
154            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
155            /** @brief Returns the begin-iterator of the direct-children-list. @return The begin-iterator */
156            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
157            /** @brief Returns the end-iterator of the direct-children-list. @return The end-iterator */
158            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_.end(); }
159
160
161            //////////////////////////
162            ///// Identifier Map /////
163            //////////////////////////
164            static void destroyAllIdentifiers();
165
166            static Identifier* getIdentifierByString(const std::string& name);
167            static Identifier* getIdentifierByLowercaseString(const std::string& name);
168            static Identifier* getIdentifierByID(uint32_t id);
169
170            static void clearNetworkIDs();
171
172            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
173            static inline const std::map<std::string, Identifier*>& getStringIdentifierMap() { return Identifier::getStringIdentifierMapIntern(); }
174            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names. @return The const_iterator */
175            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapBegin() { return Identifier::getStringIdentifierMap().begin(); }
176            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names. @return The const_iterator */
177            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapEnd() { return Identifier::getStringIdentifierMap().end(); }
178
179            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
180            static inline const std::map<std::string, Identifier*>& getLowercaseStringIdentifierMap() { return Identifier::getLowercaseStringIdentifierMapIntern(); }
181            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
182            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapBegin() { return Identifier::getLowercaseStringIdentifierMap().begin(); }
183            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
184            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapEnd() { return Identifier::getLowercaseStringIdentifierMap().end(); }
185
186            /** @brief Returns the map that stores all Identifiers with their IDs. @return The map */
187            static inline const std::map<uint32_t, Identifier*>& getIDIdentifierMap() { return Identifier::getIDIdentifierMapIntern(); }
188            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their IDs. @return The const_iterator */
189            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapBegin() { return Identifier::getIDIdentifierMap().begin(); }
190            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their IDs. @return The const_iterator */
191            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapEnd() { return Identifier::getIDIdentifierMap().end(); }
192
193
194            /////////////////////////
195            ///// Config Values /////
196            /////////////////////////
197            virtual void updateConfigValues(bool updateChildren = true) const = 0;
198
199            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
200            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
201
202            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
203            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
204
205
206            ///////////////////
207            ///// XMLPort /////
208            ///////////////////
209            /** @brief Returns the map that stores all XMLPort params. @return The const_iterator */
210            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
211            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort params. @return The const_iterator */
212            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
213            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort params. @return The const_iterator */
214            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
215
216            /** @brief Returns the map that stores all XMLPort objects. @return The const_iterator */
217            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
218            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort objects. @return The const_iterator */
219            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
220            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort objects. @return The const_iterator */
221            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
222
223            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
224            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
225
226            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
227            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
228
229
230        protected:
231            Identifier();
232            Identifier(const Identifier& identifier); // don't copy
233            virtual ~Identifier();
234
235            static Identifier* getIdentifierSingleton(const std::string& name, Identifier* proposal);
236            virtual void createSuperFunctionCaller() const = 0;
237
238            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
239
240            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
241            static std::map<std::string, Identifier*>& getStringIdentifierMapIntern();
242            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
243            static std::map<std::string, Identifier*>& getLowercaseStringIdentifierMapIntern();
244            /** @brief Returns the map that stores all Identifiers with their network IDs. @return The map */
245            static std::map<uint32_t, Identifier*>& getIDIdentifierMapIntern();
246
247            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
248            inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
249            /** @brief Returns the direct children of the class the Identifier belongs to. @return The list of all direct children */
250            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
251
252            ObjectListBase* objects_;                                      //!< The list of all objects of this class
253
254        private:
255            /** @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents. */
256            inline static void startCreatingHierarchy() { hierarchyCreatingCounter_s++; }
257            /** @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents. */
258            inline static void stopCreatingHierarchy()  { hierarchyCreatingCounter_s--; }
259
260            static std::map<std::string, Identifier*>& getTypeIDIdentifierMap();
261
262            void initialize(std::set<const Identifier*>* parents);
263
264            std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
265            mutable std::set<const Identifier*> children_;                 //!< The children of the class the Identifier belongs to
266
267            std::set<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to
268            mutable std::set<const Identifier*> directChildren_;           //!< The direct children of the class the Identifier belongs to
269
270            bool bCreatedOneObject_;                                       //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
271            bool bSetName_;                                                //!< True if the name is set
272            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
273            std::string name_;                                             //!< The name of the class the Identifier belongs to
274            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
275            static int hierarchyCreatingCounter_s;                         //!< Bigger than zero if at least one Identifier stores its parents (its an int instead of a bool to avoid conflicts with multithreading)
276            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
277            const unsigned int classID_;                                   //!< Uniquely identifies a class (might not be the same as the networkID_)
278            static unsigned int classIDCounter_s;                          //!< Static counter for the unique classIDs
279
280            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
281            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
282
283            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
284            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
285    };
286
287    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
288
289
290    // ###############################
291    // ###     ClassIdentifier     ###
292    // ###############################
293    //! The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
294    /**
295        ClassIdentifier is a Singleton, which means that only one object of a given type T exists.
296        This makes it possible to store information about a class, sharing them with all
297        objects of that class without defining static variables in every class.
298
299        To be really sure that not more than exactly one object exists (even with libraries),
300        ClassIdentifiers are stored in the Identifier Singleton.
301    */
302    template <class T>
303    class ClassIdentifier : public Identifier
304    {
305        #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
306        #include "Super.h"
307
308        public:
309            static ClassIdentifier<T>* getIdentifier();
310            static ClassIdentifier<T>* getIdentifier(const std::string& name);
311
312            bool initialiseObject(T* object, const std::string& className, bool bRootClass);
313
314            void updateConfigValues(bool updateChildren = true) const;
315
316        private:
317            static void initialiseIdentifier();
318            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
319            ClassIdentifier()
320            {
321                SuperFunctionInitialization<0, T>::initialize(this);
322            }
323            ~ClassIdentifier()
324            {
325                SuperFunctionDestruction<0, T>::destroy(this);
326            }
327
328            static ClassIdentifier<T>* classIdentifier_s;
329    };
330
331    template <class T>
332    ClassIdentifier<T>* ClassIdentifier<T>::classIdentifier_s = 0;
333
334    /**
335        @brief Returns the only instance of this class.
336        @return The unique Identifier
337    */
338    template <class T>
339    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
340    {
341        // check if the Identifier already exists
342        if (!ClassIdentifier<T>::classIdentifier_s)
343            ClassIdentifier<T>::initialiseIdentifier();
344
345        return ClassIdentifier<T>::classIdentifier_s;
346    }
347
348    /**
349        @brief Does the same as getIdentifier() but sets the name if this wasn't done yet.
350        @param name The name of this Identifier
351        @return The Identifier
352    */
353    template <class T>
354    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier(const std::string& name)
355    {
356        ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
357        identifier->setName(name);
358        return identifier;
359    }
360
361    /**
362        @brief Assigns the static field for the identifier singleton.
363    */
364    template <class T>
365    void ClassIdentifier<T>::initialiseIdentifier()
366    {
367        // Get the name of the class
368        const std::string& name = typeid(T).name();
369
370        // create a new identifier anyway. Will be deleted in Identifier::getIdentifier if not used.
371        ClassIdentifier<T>* proposal = new ClassIdentifier<T>();
372
373        // Get the entry from the map
374        ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*)Identifier::getIdentifierSingleton(name, proposal);
375
376        if (ClassIdentifier<T>::classIdentifier_s == proposal)
377        {
378            COUT(4) << "*** Identifier: Requested Identifier for " << name << " was not yet existing and got created." << std::endl;
379        }
380        else
381        {
382            COUT(4) << "*** Identifier: Requested Identifier for " << name << " was already existing and got assigned." << std::endl;
383        }
384    }
385
386    /**
387        @brief Adds an object of the given type to the ObjectList.
388        @param object The object to add
389    */
390    template <class T>
391    bool ClassIdentifier<T>::initialiseObject(T* object, const std::string& className, bool bRootClass)
392    {
393        if (bRootClass)
394            COUT(5) << "*** Register Root-Object: " << className << std::endl;
395        else
396            COUT(5) << "*** Register Object: " << className << std::endl;
397
398        object->identifier_ = this;
399        if (Identifier::isCreatingHierarchy())
400        {
401            if (bRootClass && !object->parents_)
402                object->parents_ = new std::set<const Identifier*>();
403
404            if (object->parents_)
405            {
406                this->initializeClassHierarchy(object->parents_, bRootClass);
407                object->parents_->insert(object->parents_->end(), this);
408            }
409
410            object->setConfigValues();
411            return true;
412        }
413        else
414        {
415            COUT(5) << "*** ClassIdentifier: Added object to " << this->getName() << "-list." << std::endl;
416            object->metaList_->add(this->objects_, this->objects_->add(new ObjectListElement<T>(object)));
417
418            // Add pointer of type T to the map in the OrxonoxClass instance that enables "dynamic_casts"
419            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
420            return false;
421        }
422    }
423
424    /**
425        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
426    */
427    template <class T>
428    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
429    {
430        if (!this->hasConfigValues())
431            return;
432
433        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
434            it->setConfigValues();
435
436        if (updateChildren)
437            for (std::set<const Identifier*>::const_iterator it = this->getChildrenBegin(); it != this->getChildrenEnd(); ++it)
438                (*it)->updateConfigValues(false);
439    }
440
441
442    // ###############################
443    // ###      orxonox_cast       ###
444    // ###############################
445    /**
446    @brief
447        Casts on object of type OrxonoxClass to any derived type that is
448        registered in the class hierarchy.
449    @return
450        Returns NULL if the cast is not possible
451    @note
452        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
453        a class forgot to register its objects.
454        Also note that the function is implemented differently for GCC/MSVC.
455    */
456    template <class T, class U>
457    FORCEINLINE T orxonox_cast(U* source)
458    {
459#ifdef ORXONOX_COMPILER_MSVC
460        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
461        if (source != NULL)
462            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
463        else
464            return NULL;
465#else
466        return dynamic_cast<T>(source);
467#endif
468    }
469}
470
471#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.