Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/class/Identifier.h @ 10377

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

added a check which tries to detect wrongly configured class hierarchy definitions

  • Property svn:eol-style set to native
File size: 20.3 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    @defgroup Identifier Identifier
31    @ingroup Class
32*/
33
34/**
35    @file
36    @ingroup Class Identifier
37    @brief Declaration of Identifier, definition of ClassIdentifier<T>; used to identify the class of an object.
38
39    @anchor IdentifierExample
40
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.
44
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.
48
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
58    Identifiable* other = object->getIdentifier()->fabricate(0);                // fabricates a new instance of MyClass
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
69*/
70
71#ifndef _Identifier_H__
72#define _Identifier_H__
73
74#include "core/CorePrereqs.h"
75
76#include <cassert>
77#include <map>
78#include <set>
79#include <string>
80#include <typeinfo>
81#include <loki/TypeTraits.h>
82
83#include "util/Output.h"
84#include "core/object/ObjectList.h"
85#include "core/object/Listable.h"
86#include "core/object/Context.h"
87#include "core/object/Destroyable.h"
88#include "core/object/WeakPtr.h"
89#include "IdentifierManager.h"
90#include "Super.h"
91
92namespace orxonox
93{
94    // ###############################
95    // ###       Identifier        ###
96    // ###############################
97    /**
98        @brief The Identifier is used to identify the class of an object and to store information about the class.
99
100        Each Identifier stores information about one class. The Identifier can then be used to identify
101        this class. On the other hand it's also possible to get the corresponding Identifier of a class,
102        for example by using the macro Class().
103
104        @see See @ref IdentifierExample "Identifier.h" for more information and some examples.
105
106        @note You can't directly create an Identifier, it's just the base-class of ClassIdentifier<T>.
107    */
108    class _CoreExport Identifier : public Destroyable
109    {
110        public:
111            Identifier();
112            Identifier(const Identifier& identifier); // don't copy
113            virtual ~Identifier();
114
115            /// Returns the name of the class the Identifier belongs to.
116            inline const std::string& getName() const { return this->name_; }
117            void setName(const std::string& name);
118
119            /// Returns the name of the class as it is returned by typeid(T).name()
120            virtual const std::string& getTypeidName() = 0;
121
122            /// Returns the network ID to identify a class through the network.
123            inline uint32_t getNetworkID() const { return this->networkID_; }
124            void setNetworkID(uint32_t id);
125
126            /// Returns the unique ID of the class.
127            ORX_FORCEINLINE unsigned int getClassID() const { return this->classID_; }
128
129            /// Sets the Factory.
130            void setFactory(Factory* factory);
131            /// Returns true if the Identifier has a Factory.
132            inline bool hasFactory() const { return (this->factory_ != 0); }
133
134            Identifiable* fabricate(Context* context);
135
136            /// Returns true if the class can be loaded through XML.
137            inline bool isLoadable() const { return this->bLoadable_; }
138            /// Set the class to be loadable through XML or not.
139            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
140
141            /// Returns true if child classes should inherit virtually from this class.
142            inline bool isVirtualBase() const { return this->bIsVirtualBase_; }
143            /// Defines if child classes should inherit virtually from this class.
144            inline void setVirtualBase(bool bIsVirtualBase) { this->bIsVirtualBase_ = bIsVirtualBase; }
145
146            /// Returns true if the Identifier was completely initialized.
147            inline bool isInitialized() const { return this->bInitialized_; }
148
149
150            /////////////////////////////
151            ////// Class Hierarchy //////
152            /////////////////////////////
153            Identifier& inheritsFrom(Identifier* directParent);
154
155            void initializeParents(const std::list<const Identifier*>& initializationTrace);
156            void finishInitialization();
157
158            bool isA(const Identifier* identifier) const;
159            bool isExactlyA(const Identifier* identifier) const;
160            bool isChildOf(const Identifier* identifier) const;
161            bool isDirectChildOf(const Identifier* identifier) const;
162            bool isParentOf(const Identifier* identifier) const;
163            bool isDirectParentOf(const Identifier* identifier) const;
164
165            /// Returns the direct parents of the class the Identifier belongs to.
166            inline const std::list<const Identifier*>& getDirectParents() const { return this->directParents_; }
167            /// Returns the parents of the class the Identifier belongs to.
168            inline const std::list<const Identifier*>& getParents() const { return this->parents_; }
169
170            /// Returns the direct children the class the Identifier belongs to.
171            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
172            /// Returns the children of the class the Identifier belongs to.
173            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
174
175
176            /////////////////////////
177            ///// Config Values /////
178            /////////////////////////
179            virtual void updateConfigValues(bool updateChildren = true) const = 0;
180
181            /// Returns true if this class has at least one config value.
182            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
183
184            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
185            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
186
187
188            ///////////////////
189            ///// XMLPort /////
190            ///////////////////
191            /// Returns the map that stores all XMLPort params.
192            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
193            /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
194            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
195            /// Returns a const_iterator to the end of the map that stores all XMLPort params.
196            inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
197
198            /// Returns the map that stores all XMLPort objects.
199            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
200            /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
201            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
202            /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
203            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
204
205            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
206            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
207
208            void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
209            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
210
211            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const = 0;
212
213        protected:
214            virtual void createSuperFunctionCaller() const = 0;
215
216        private:
217            void verifyIdentifierTrace() const;
218            void addIfNotExists(std::list<const Identifier*>& list, const Identifier* identifierToAdd) const;
219
220            std::list<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to (sorted by their order of initialization)
221            std::list<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to (sorted by their order of initialization)
222
223            std::set<const Identifier*> directChildren_;                   //!< The direct children of the class the Identifier belongs to
224            std::set<const Identifier*> children_;                         //!< The children of the class the Identifier belongs to
225
226            bool bInitialized_;                                            //!< Is true if the Identifier was completely initialized
227            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
228            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.
229            std::string name_;                                             //!< The name of the class the Identifier belongs to
230            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
231            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
232            const unsigned int classID_;                                   //!< Uniquely identifies a class (might not be the same as the networkID_)
233
234            bool bHasConfigValues_;                                        //!< True if this class has at least one assigned config value
235            std::map<std::string, ConfigValueContainer*> configValues_;    //!< A map to link the string of configurable variables with their ConfigValueContainer
236
237            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
238            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
239    };
240
241    _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
242
243
244    // ###############################
245    // ###     ClassIdentifier     ###
246    // ###############################
247    /**
248        @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
249
250        ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
251        This makes it possible to store information about a class, sharing them with all
252        objects of that class without defining static variables in every class.
253
254        To be really sure that not more than exactly one object exists (even with libraries),
255        ClassIdentifiers are stored in a static map in Identifier.
256    */
257    template <class T>
258    class ClassIdentifier : public Identifier
259    {
260        #ifndef DOXYGEN_SHOULD_SKIP_THIS
261          #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
262          #include "Super.h"
263        #endif
264
265        public:
266            static ClassIdentifier<T>* getIdentifier();
267            static ClassIdentifier<T>* getIdentifier(const std::string& name);
268
269            bool initializeObject(T* object);
270
271            void setConfigValues(T* object, Configurable*) const;
272            void setConfigValues(T* object, Identifiable*) const;
273
274            void addObjectToList(T* object, Listable*);
275            void addObjectToList(T* object, Identifiable*);
276
277            virtual void updateConfigValues(bool updateChildren = true) const;
278
279            virtual const std::string& getTypeidName()
280                { return this->typeidName_; }
281
282            virtual bool canDynamicCastObjectToIdentifierClass(Identifiable* object) const
283                { return dynamic_cast<T*>(object) != 0; }
284
285        private:
286            static void initializeIdentifier();
287
288            ClassIdentifier(const ClassIdentifier<T>& identifier) {}    // don't copy
289            ClassIdentifier()
290            {
291                this->typeidName_ = typeid(T).name();
292                SuperFunctionInitialization<0, T>::initialize(this);
293            }
294            ~ClassIdentifier()
295            {
296                SuperFunctionDestruction<0, T>::destroy(this);
297            }
298
299            void updateConfigValues(bool updateChildren, Listable*) const;
300            void updateConfigValues(bool updateChildren, Identifiable*) const;
301
302            std::string typeidName_;
303            static WeakPtr<ClassIdentifier<T> > classIdentifier_s;
304    };
305
306    template <class T>
307    WeakPtr<ClassIdentifier<T> > ClassIdentifier<T>::classIdentifier_s;
308
309    /**
310        @brief Returns the only instance of this class.
311        @return The unique Identifier
312    */
313    template <class T>
314    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
315    {
316        // check if the Identifier already exists
317        if (!ClassIdentifier<T>::classIdentifier_s)
318            ClassIdentifier<T>::initializeIdentifier();
319
320        return ClassIdentifier<T>::classIdentifier_s;
321    }
322
323    /**
324        @brief Does the same as getIdentifier() but sets the name if this wasn't done yet.
325        @param name The name of this Identifier
326        @return The Identifier
327    */
328    template <class T>
329    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier(const std::string& name)
330    {
331        ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
332        identifier->setName(name);
333        return identifier;
334    }
335
336    /**
337        @brief Assigns the static field for the identifier singleton.
338    */
339    template <class T>
340    /*static */ void ClassIdentifier<T>::initializeIdentifier()
341    {
342        // create a new identifier anyway. Will be deleted if not used.
343        ClassIdentifier<T>* proposal = new ClassIdentifier<T>();
344
345        // Get the entry from the map
346        ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*)IdentifierManager::getInstance().getGloballyUniqueIdentifier(proposal);
347
348        if (ClassIdentifier<T>::classIdentifier_s == proposal)
349            orxout(verbose, context::identifier) << "Requested Identifier for " << proposal->getTypeidName() << " was not yet existing and got created." << endl;
350        else
351        {
352            orxout(verbose, context::identifier) << "Requested Identifier for " << proposal->getTypeidName() << " was already existing and got assigned." << endl;
353            delete proposal; // delete proposal (it is not used anymore)
354        }
355    }
356
357    /**
358        @brief Adds an object of the given type to the ObjectList.
359        @param object The object to add
360    */
361    template <class T>
362    bool ClassIdentifier<T>::initializeObject(T* object)
363    {
364        orxout(verbose, context::object_list) << "Register Object: " << this->getName() << endl;
365
366        object->identifier_ = this;
367        if (IdentifierManager::getInstance().isCreatingHierarchy())
368        {
369            IdentifierManager::getInstance().createdObject(object);
370
371            this->setConfigValues(object, object);
372            return true;
373        }
374        else
375        {
376            this->addObjectToList(object, object);
377
378            // Add pointer of type T to the map in the Identifiable instance that enables "dynamic_casts"
379            object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
380            return false;
381        }
382    }
383
384    /**
385     * @brief Only configures the object if is a @ref Configurable
386     */
387    template <class T>
388    void ClassIdentifier<T>::setConfigValues(T* object, Configurable*) const
389    {
390        object->setConfigValues();
391    }
392
393    template <class T>
394    void ClassIdentifier<T>::setConfigValues(T*, Identifiable*) const
395    {
396        // no action
397    }
398
399    /**
400     * @brief Only adds the object to the object list if is a @ref Listable
401     */
402    template <class T>
403    void ClassIdentifier<T>::addObjectToList(T* object, Listable* listable)
404    {
405        if (listable->getContext())
406            listable->getContext()->addObject(object);
407    }
408
409    template <class T>
410    void ClassIdentifier<T>::addObjectToList(T*, Identifiable*)
411    {
412        // no action
413    }
414
415    /**
416        @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
417    */
418    template <class T>
419    void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
420    {
421        this->updateConfigValues(updateChildren, static_cast<T*>(NULL));
422    }
423
424    template <class T>
425    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Listable*) const
426    {
427        if (!this->hasConfigValues())
428            return;
429
430        for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
431            this->setConfigValues(*it, *it);
432
433        if (updateChildren)
434            for (std::set<const Identifier*>::const_iterator it = this->getChildren().begin(); it != this->getChildren().end(); ++it)
435                (*it)->updateConfigValues(false);
436    }
437
438    template <class T>
439    void ClassIdentifier<T>::updateConfigValues(bool updateChildren, Identifiable*) const
440    {
441        // no action
442    }
443
444
445    // ###############################
446    // ###      orxonox_cast       ###
447    // ###############################
448    /**
449    @brief
450        Casts on object of type Identifiable to any derived type that is
451        registered in the class hierarchy.
452    @return
453        Returns NULL if the cast is not possible
454    @note
455        In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
456        a class forgot to register its objects.
457        Also note that the function is implemented differently for GCC/MSVC.
458    */
459    template <class T, class U>
460    ORX_FORCEINLINE T orxonox_cast(U* source)
461    {
462#ifdef ORXONOX_COMPILER_MSVC
463        typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
464        if (source != NULL)
465            return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
466        else
467            return NULL;
468#else
469        return dynamic_cast<T>(source);
470#endif
471    }
472}
473
474#endif /* _Identifier_H__ */
Note: See TracBrowser for help on using the repository browser.