Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10624 was 10624, checked in by landauf, 9 years ago

merged branch core7 back to trunk

  • Property svn:eol-style set to native
File size: 21.2 KB
RevLine 
[790]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1505]3 *                    > www.orxonox.net <
[790]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
[871]29/**
[7401]30    @defgroup Identifier Identifier
31    @ingroup Class
32*/
33
34/**
[2171]35    @file
[7401]36    @ingroup Class Identifier
37    @brief Declaration of Identifier, definition of ClassIdentifier<T>; used to identify the class of an object.
[790]38
[7401]39    @anchor IdentifierExample
[790]40
[7401]41    An Identifier "identifies" the class of an object. It contains different information about
42    the class: Its name and ID, a list of all instances of this class, a factory to create new
43    instances of this class, and more.
[790]44
[7401]45    It also contains information about the inheritance of this class: It stores a list of the
46    Identifiers of all parent-classes as well as a list of all child-classes. These relationships
47    can be tested using functions like @c isA(), @c isChildOf(), @c isParentOf(), and more.
[790]48
[7401]49    Every Identifier is in fact a ClassIdentifier<T> (where T is the class that is identified
50    by the Identifier), Identifier is just the common base-class.
51
52    Example:
53    @code
54    MyClass* object = new MyClass();                                            // create an instance of MyClass
55
56    object->getIdentifier()->getName();                                         // returns "MyClass"
57
[9667]58    Identifiable* other = object->getIdentifier()->fabricate(0);                // fabricates a new instance of MyClass
[7401]59
60
61    // test the class hierarchy
62    object->getIdentifier()->isA(Class(MyClass));                               // returns true
63    object->isA(Class(MyClass));                                                // returns true (short version)
64
65    object->isA(Class(BaseClass));                                              // returns true if MyClass is a child of BaseClass
66
67    Class(ChildClass)->isChildOf(object->getIdentifier());                      // returns true if ChildClass is a child of MyClass
68    @endcode
[790]69*/
70
71#ifndef _Identifier_H__
72#define _Identifier_H__
[1052]73
[9563]74#include "core/CorePrereqs.h"
[1062]75
[3196]76#include <cassert>
77#include <map>
[1052]78#include <set>
[790]79#include <string>
[1639]80#include <typeinfo>
[7266]81#include <loki/TypeTraits.h>
[10624]82#include <boost/static_assert.hpp>
83#include <boost/type_traits/is_base_of.hpp>
[790]84
[8858]85#include "util/Output.h"
[10624]86#include "util/OrxAssert.h"
[9563]87#include "core/object/ObjectList.h"
[9667]88#include "core/object/Listable.h"
89#include "core/object/Context.h"
90#include "core/object/Destroyable.h"
91#include "core/object/WeakPtr.h"
[9564]92#include "IdentifierManager.h"
[5781]93#include "Super.h"
[790]94
95namespace orxonox
96{
97    // ###############################
98    // ###       Identifier        ###
99    // ###############################
100    /**
[7401]101        @brief The Identifier is used to identify the class of an object and to store information about the class.
[790]102
[7401]103        Each Identifier stores information about one class. The Identifier can then be used to identify
104        this class. On the other hand it's also possible to get the corresponding Identifier of a class,
105        for example by using the macro Class().
[790]106
[7401]107        @see See @ref IdentifierExample "Identifier.h" for more information and some examples.
108
109        @note You can't directly create an Identifier, it's just the base-class of ClassIdentifier<T>.
[790]110    */
[9667]111    class _CoreExport Identifier : public Destroyable
[790]112    {
[9667]113        public:
[10624]114            struct InheritsFrom //! helper class to manually define inheritance
115            {
116                virtual ~InheritsFrom() {}
117                virtual Identifier* getParent() const = 0;
118            };
119
120        public:
121            Identifier(const std::string& name, Factory* factory, bool bLoadable);
[9667]122            Identifier(const Identifier& identifier); // don't copy
123            virtual ~Identifier();
[9564]124
[7401]125            /// Returns the name of the class the Identifier belongs to.
[5929]126            inline const std::string& getName() const { return this->name_; }
[790]127
[10624]128            /// Returns the type_info of the class as it is returned by typeid(T)
129            virtual const std::type_info& getTypeInfo() = 0;
[9667]130
[7401]131            /// Returns the network ID to identify a class through the network.
[8706]132            inline uint32_t getNetworkID() const { return this->networkID_; }
[5929]133            void setNetworkID(uint32_t id);
[790]134
[7401]135            /// Returns the unique ID of the class.
[8351]136            ORX_FORCEINLINE unsigned int getClassID() const { return this->classID_; }
[5929]137
[7401]138            /// Returns true if the Identifier has a Factory.
[5929]139            inline bool hasFactory() const { return (this->factory_ != 0); }
[790]140
[9667]141            Identifiable* fabricate(Context* context);
[5929]142
[7401]143            /// Returns true if the class can be loaded through XML.
[5929]144            inline bool isLoadable() const { return this->bLoadable_; }
145
[10624]146            /// Returns true if child classes should inherit virtually from this class.
147            inline bool isVirtualBase() const { return this->bIsVirtualBase_; }
148            /// Defines if child classes should inherit virtually from this class.
149            inline void setVirtualBase(bool bIsVirtualBase) { this->bIsVirtualBase_ = bIsVirtualBase; }
150
[9667]151            /// Returns true if the Identifier was completely initialized.
152            inline bool isInitialized() const { return this->bInitialized_; }
153
[10624]154            virtual void destroyObjects() = 0;
[9667]155
[10624]156            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const = 0;
157
158            static bool initConfigValues_s; // TODO: this is a hack - remove it as soon as possible
159
160
[9667]161            /////////////////////////////
162            ////// Class Hierarchy //////
163            /////////////////////////////
[10624]164            Identifier& inheritsFrom(InheritsFrom* directParent);
[9667]165
[10624]166            void initializeParents(const std::list<const Identifier*>& initializationTrace);
[9667]167            void finishInitialization();
[10624]168            void reset();
[9667]169
[790]170            bool isA(const Identifier* identifier) const;
[871]171            bool isExactlyA(const Identifier* identifier) const;
[1052]172            bool isChildOf(const Identifier* identifier) const;
[871]173            bool isDirectChildOf(const Identifier* identifier) const;
[1052]174            bool isParentOf(const Identifier* identifier) const;
[871]175            bool isDirectParentOf(const Identifier* identifier) const;
[790]176
[10624]177            /// Returns the direct parents of the class the Identifier belongs to.
178            inline const std::list<const Identifier*>& getDirectParents() const { return this->directParents_; }
[7401]179            /// Returns the parents of the class the Identifier belongs to.
[10624]180            inline const std::list<const Identifier*>& getParents() const { return this->parents_; }
[1052]181
[10624]182            /// Returns the direct children the class the Identifier belongs to.
183            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
[7401]184            /// Returns the children of the class the Identifier belongs to.
[5929]185            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
[1052]186
187
[5929]188            /////////////////////////
189            ///// Config Values /////
190            /////////////////////////
191            virtual void updateConfigValues(bool updateChildren = true) const = 0;
192
[7401]193            /// Returns true if this class has at least one config value.
[5929]194            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
195
196            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
197            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
[1052]198
[5929]199
200            ///////////////////
201            ///// XMLPort /////
202            ///////////////////
[7401]203            /// Returns the map that stores all XMLPort params.
[5781]204            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
[7401]205            /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
[5781]206            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
[7401]207            /// Returns a const_iterator to the end of the map that stores all XMLPort params.
[5781]208            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
209
[7401]210            /// Returns the map that stores all XMLPort objects.
[5781]211            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
[7401]212            /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
[5781]213            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
[7401]214            /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
[5781]215            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
216
217            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
218            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
219
220            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
221            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
222
[1052]223        protected:
[5781]224            virtual void createSuperFunctionCaller() const = 0;
[1747]225
226        private:
[10624]227            void verifyIdentifierTrace() const;
228            void addIfNotExists(std::list<const Identifier*>& list, const Identifier* identifierToAdd) const;
[790]229
[10624]230            std::list<const InheritsFrom*> manualDirectParents_;            //!< Manually defined direct parents
231            std::list<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to (sorted by their order of initialization)
232            std::list<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to (sorted by their order of initialization)
233
[9667]234            std::set<const Identifier*> directChildren_;                   //!< The direct children of the class the Identifier belongs to
[10624]235            std::set<const Identifier*> children_;                         //!< The children of the class the Identifier belongs to
[1052]236
[9667]237            bool bInitialized_;                                            //!< Is true if the Identifier was completely initialized
[5781]238            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
[10624]239            bool bIsVirtualBase_;                                          //!< If true, it is recommended to inherit virtually from this class. This changes the order of initialization of child classes, thus this information is necessary to check the class hierarchy.
[1052]240            std::string name_;                                             //!< The name of the class the Identifier belongs to
[5929]241            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
[5781]242            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
[10624]243            unsigned int classID_;                                         //!< Uniquely identifies a class (might not be the same as the networkID_)
[1052]244
245            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
246            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
[5781]247
248            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
249            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
[790]250    };
251
[1052]252    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
[790]253
[1052]254
[790]255    // ###############################
256    // ###     ClassIdentifier     ###
257    // ###############################
258    /**
[7401]259        @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
260
261        ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
[5695]262        This makes it possible to store information about a class, sharing them with all
[1052]263        objects of that class without defining static variables in every class.
264
265        To be really sure that not more than exactly one object exists (even with libraries),
[7401]266        ClassIdentifiers are stored in a static map in Identifier.
[790]267    */
268    template <class T>
269    class ClassIdentifier : public Identifier
[1052]270    {
[10624]271        BOOST_STATIC_ASSERT((boost::is_base_of<Identifiable, T>::value));
272
[7401]273        #ifndef DOXYGEN_SHOULD_SKIP_THIS
274          #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
275          #include "Super.h"
276        #endif
[5781]277
[790]278        public:
[10624]279            ClassIdentifier(const std::string& name, Factory* factory, bool bLoadable) : Identifier(name, factory, bLoadable)
280            {
281                OrxVerify(ClassIdentifier<T>::classIdentifier_s == NULL, "Assertion failed in ClassIdentifier of type " << typeid(T).name());
282                ClassIdentifier<T>::classIdentifier_s = this;
[1052]283
[10624]284                SuperFunctionInitialization<0, T>::initialize(this);
285            }
286            ~ClassIdentifier()
287            {
288                SuperFunctionDestruction<0, T>::destroy(this);
289            }
290
[9667]291            bool initializeObject(T* object);
[3325]292
[10624]293            virtual void updateConfigValues(bool updateChildren = true) const;
294
295            virtual const std::type_info& getTypeInfo()
296                { return typeid(T); }
297
298            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const
299                { return dynamic_cast<T*>(object) != 0; }
300
301            virtual void destroyObjects();
302
303            static ClassIdentifier<T>* getIdentifier();
304
305        private:
306            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
307
[9586]308            void setConfigValues(T* object, Configurable*) const;
309            void setConfigValues(T* object, Identifiable*) const;
310
[9572]311            void addObjectToList(T* object, Listable*);
312            void addObjectToList(T* object, Identifiable*);
313
[10624]314            void destroyObjects(Listable*);
315            void destroyObjects(void*);
[1052]316
[10624]317            void destroyObject(Destroyable* object);
318            void destroyObject(void* object);
[9667]319
320            void updateConfigValues(bool updateChildren, Listable*) const;
321            void updateConfigValues(bool updateChildren, Identifiable*) const;
322
323            static WeakPtr<ClassIdentifier<T> > classIdentifier_s;
[790]324    };
325
[1543]326    template <class T>
[9667]327    WeakPtr<ClassIdentifier<T> > ClassIdentifier<T>::classIdentifier_s;
[1543]328
[790]329    /**
[1747]330        @brief Returns the only instance of this class.
[1543]331        @return The unique Identifier
332    */
333    template <class T>
[10624]334    /*static*/ inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
[1543]335    {
[10624]336        if (ClassIdentifier<T>::classIdentifier_s == NULL)
337            ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*) IdentifierManager::getInstance().getIdentifierByTypeInfo(typeid(T));
[1543]338
[10624]339        OrxVerify(ClassIdentifier<T>::classIdentifier_s != NULL, "Did you forget to register the class of type " << typeid(T).name() << "?");
[1543]340        return ClassIdentifier<T>::classIdentifier_s;
341    }
342
343    /**
[790]344        @brief Adds an object of the given type to the ObjectList.
345        @param object The object to add
346    */
347    template <class T>
[9667]348    bool ClassIdentifier<T>::initializeObject(T* object)
[790]349    {
[9667]350        orxout(verbose, context::object_list) << "Register Object: " << this->getName() << endl;
[3325]351
352        object->identifier_ = this;
[9667]353        if (IdentifierManager::getInstance().isCreatingHierarchy())
[3325]354        {
[9667]355            IdentifierManager::getInstance().createdObject(object);
[3325]356
[10624]357            if (Identifier::initConfigValues_s)
358                this->setConfigValues(object, object);
359
[3325]360            return true;
361        }
362        else
363        {
[9572]364            this->addObjectToList(object, object);
[3325]365
[9566]366            // Add pointer of type T to the map in the Identifiable instance that enables "dynamic_casts"
[3333]367            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
[3325]368            return false;
369        }
[790]370    }
371
372    /**
[9586]373     * @brief Only configures the object if is a @ref Configurable
374     */
375    template <class T>
376    void ClassIdentifier<T>::setConfigValues(T* object, Configurable*) const
377    {
378        object->setConfigValues();
379    }
380
381    template <class T>
382    void ClassIdentifier<T>::setConfigValues(T*, Identifiable*) const
383    {
384        // no action
385    }
386
387    /**
[9572]388     * @brief Only adds the object to the object list if is a @ref Listable
389     */
390    template <class T>
[9667]391    void ClassIdentifier<T>::addObjectToList(T* object, Listable* listable)
[9572]392    {
[9667]393        if (listable->getContext())
394            listable->getContext()->addObject(object);
[9572]395    }
396
397    template <class T>
398    void ClassIdentifier<T>::addObjectToList(T*, Identifiable*)
399    {
400        // no action
401    }
402
403    /**
[10624]404     * @brief Destroy all objects of this class (must be Listable).
405     * Destroyables are destroyed with destroy(), all other classes with delete.
406     */
407    template <class T>
408    void ClassIdentifier<T>::destroyObjects()
409    {
410        this->destroyObjects((T*)0);
411    }
412
413    /**
414     * @brief Only searches and destroys objects if is a @ref Listable
415     */
416    template <class T>
417    void ClassIdentifier<T>::destroyObjects(Listable*)
418    {
419        ObjectListBase* objectList = Context::getRootContext()->getObjectList(this);
420        ObjectListElement<T>* begin = static_cast<ObjectListElement<T>*>(objectList->begin());
421        ObjectListElement<T>* end = static_cast<ObjectListElement<T>*>(objectList->end());
422        for (typename ObjectList<T>::iterator it = begin; it != end; )
423            this->destroyObject(*(it++));
424    }
425
426    template <class T>
427    void ClassIdentifier<T>::destroyObjects(void*)
428    {
429        // no action
430    }
431
432    /**
433     * @brief Call 'object->destroy()' for Destroyables and 'delete object' for all other types.
434     */
435    template <class T>
436    void ClassIdentifier<T>::destroyObject(Destroyable* object)
437    {
438        object->destroy();
439    }
440
441    template <class T>
442    void ClassIdentifier<T>::destroyObject(void* object)
443    {
444        delete static_cast<Identifiable*>(object);
445    }
446
447    /**
[1052]448        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
[790]449    */
450    template <class T>
[1747]451    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
[790]452    {
[9667]453        this->updateConfigValues(updateChildren, static_cast<T*>(NULL));
454    }
455
456    template <class T>
457    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Listable*) const
458    {
[1747]459        if (!this->hasConfigValues())
460            return;
[790]461
[1747]462        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
[9586]463            this->setConfigValues(*it, *it);
[1052]464
[1747]465        if (updateChildren)
[10624]466            for (std::set<const Identifier*>::const_iterator it = this->getChildren().begin(); it != this->getChildren().end(); ++it)
[1747]467                (*it)->updateConfigValues(false);
[1052]468    }
469
[9667]470    template <class T>
471    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Identifiable*) const
472    {
473        // no action
474    }
[1052]475
[9667]476
[790]477    // ###############################
[3325]478    // ###      orxonox_cast       ###
479    // ###############################
480    /**
481    @brief
[9566]482        Casts on object of type Identifiable to any derived type that is
[3325]483        registered in the class hierarchy.
484    @return
485        Returns NULL if the cast is not possible
486    @note
487        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
488        a class forgot to register its objects.
489        Also note that the function is implemented differently for GCC/MSVC.
490    */
491    template <class T, class U>
[8351]492    ORX_FORCEINLINE T orxonox_cast(U* source)
[3325]493    {
[3332]494#ifdef ORXONOX_COMPILER_MSVC
[3333]495        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
[3370]496        if (source != NULL)
497            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
498        else
499            return NULL;
[3332]500#else
501        return dynamic_cast<T>(source);
502#endif
[3325]503    }
[790]504}
505
506#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.