Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core6/src/libraries/core/class/Identifier.h @ 9602

Last change on this file since 9602 was 9602, checked in by landauf, 11 years ago

delete factory before setting a new one (mostly for unit tests)

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