Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/cpp11_v3/src/libraries/core/class/Identifier.h @ 11054

Last change on this file since 11054 was 11054, checked in by landauf, 8 years ago

merged branch cpp11_v2 into cpp11_v3

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