Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Ignore:
Timestamp:
Oct 12, 2009, 8:20:07 PM (15 years ago)
Author:
rgrieder
Message:

Merged core5 branch back to the trunk.
Key features include clean level unloading and an extended XML event system.

Two important notes:
Delete your keybindings.ini files! * or you will still get parser errors when loading the key bindings.
Delete build_dir/lib/modules/libgamestates.module! * or orxonox won't start.
Best thing to do is to delete the build folder ;)

Location:
code/trunk
Files:
6 deleted
87 edited
11 copied

Legend:

Unmodified
Added
Removed
  • code/trunk

  • code/trunk/src/libraries/CMakeLists.txt

    r5781 r5929  
    2525################ Sub Directories ################
    2626
     27ADD_SUBDIRECTORY(util)
    2728ADD_SUBDIRECTORY(core)
    2829ADD_SUBDIRECTORY(network)
    2930ADD_SUBDIRECTORY(tools)
    30 ADD_SUBDIRECTORY(util)
  • code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc

    r5781 r5929  
    100100            ArgumentCompletionList classlist;
    101101
    102             for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
     102            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
    103103                if ((*it).second->hasConfigValues())
    104104                    classlist.push_back(ArgumentCompletionListElement((*it).second->getName(), getLowercase((*it).first)));
     
    110110        {
    111111            ArgumentCompletionList configvalues;
    112             std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getIdentifierMap().find(classname);
     112            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getStringIdentifierMap().find(classname);
    113113
    114             if (identifier != Identifier::getIdentifierMapEnd() && (*identifier).second->hasConfigValues())
     114            if (identifier != Identifier::getStringIdentifierMapEnd() && (*identifier).second->hasConfigValues())
    115115            {
    116116                for (std::map<std::string, ConfigValueContainer*>::const_iterator it = (*identifier).second->getConfigValueMapBegin(); it != (*identifier).second->getConfigValueMapEnd(); ++it)
     
    124124        {
    125125            ArgumentCompletionList oldvalue;
    126             std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
    127             if (identifier != Identifier::getLowercaseIdentifierMapEnd())
     126            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
     127            if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
    128128            {
    129129                std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
  • code/trunk/src/libraries/core/BaseObject.cc

    r5781 r5929  
    6363        this->bVisible_ = true;
    6464        this->oldGametype_ = 0;
     65        this->bRegisteredEventStates_ = false;
    6566
    6667        this->lastLoadedXMLElement_ = 0;
    6768
    68         this->functorSetMainState_ = 0;
    69         this->functorGetMainState_ = 0;
     69        this->mainStateFunctor_ = 0;
    7070
    7171        this->setCreator(creator);
     
    7474            this->setFile(this->creator_->getFile());
    7575            this->setNamespace(this->creator_->getNamespace());
    76             this->setScene(this->creator_->getScene());
     76            this->setScene(this->creator_->getScene(), this->creator_->getSceneID());
    7777            this->setGametype(this->creator_->getGametype());
    7878        }
     
    8282            this->namespace_ = 0;
    8383            this->scene_ = 0;
     84            this->sceneID_ = OBJECTID_UNKNOWN;
    8485            this->gametype_ = 0;
    8586        }
     
    9394        if (this->isInitialized())
    9495        {
    95             for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
    96                 (*it)->unregisterEventListener(this);
    97 
    98             for (std::map<BaseObject*, std::string>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
    99                 it->first->removeEvent(this);
    100 
    101             if (this->functorSetMainState_)
    102                 delete this->functorSetMainState_;
    103             if (this->functorGetMainState_)
    104                 delete this->functorGetMainState_;
     96            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); )
     97                this->removeEventSource((it++)->first);
     98
     99            for (std::set<BaseObject*>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); )
     100                (*(it++))->removeEventSource(this);
     101
     102            for (std::map<std::string, EventState*>::const_iterator it = this->eventStates_.begin(); it != this->eventStates_.end(); ++it)
     103                delete it->second;
    105104        }
    106105    }
     
    110109        @param xmlelement The XML-element
    111110        @param loading Loading (true) or saving (false)
    112         @return The XML-element
    113111    */
    114112    void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
     
    120118
    121119        XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
    122 
    123         Element* events = xmlelement.FirstChildElement("events", false);
    124 
     120        XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode);
     121       
     122        Element* events = 0;
     123        if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
     124            events = xmlelement.FirstChildElement("events", false);
     125        else if (mode == XMLPort::SaveObject)
     126            {}
    125127        if (events)
    126         {
    127             std::list<std::string> eventnames;
    128 
    129             if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
    130             {
    131                 for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
    132                     eventnames.push_back(child->Value());
    133             }
    134             else if (mode == XMLPort::SaveObject)
    135             {
    136                 for (std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->getIdentifier()->getXMLPortEventMapBegin(); it != this->getIdentifier()->getXMLPortEventMapEnd(); ++it)
    137                     eventnames.push_back(it->first);
    138             }
    139 
    140             for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
    141             {
    142                 std::string sectionname = (*it);
    143                 ExecutorMember<BaseObject>* loadexecutor = createExecutor(createFunctor(&BaseObject::addEvent), std::string( "BaseObject" ) + "::" + "addEvent");
    144                 ExecutorMember<BaseObject>* saveexecutor = createExecutor(createFunctor(&BaseObject::getEvent), std::string( "BaseObject" ) + "::" + "getEvent");
    145                 loadexecutor->setDefaultValue(1, sectionname);
    146 
    147                 XMLPortClassObjectContainer<BaseObject, BaseObject>* container = 0;
    148                 container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(this->getIdentifier()->getXMLPortEventContainer(sectionname));
    149                 if (!container)
    150                 {
    151                     container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(sectionname, this->getIdentifier(), loadexecutor, saveexecutor, false, true);
    152                     this->getIdentifier()->addXMLPortEventContainer(sectionname, container);
    153                 }
    154                 container->port(this, *events, mode);
    155             }
    156         }
     128            this->XMLEventPort(*events, mode);
     129    }
     130
     131    /**
     132        @brief Defines the possible event states of this object and parses eventsources from an XML file.
     133        @param xmlelement The XML-element
     134        @param loading Loading (true) or saving (false)
     135    */
     136    void BaseObject::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
     137    {
     138        XMLPortEventState(BaseObject, BaseObject, "activity", setActive, xmlelement, mode);
     139        XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode);
     140        XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode);
     141       
     142        this->bRegisteredEventStates_ = true;
    157143    }
    158144
     
    220206    }
    221207
    222     void BaseObject::addEvent(BaseObject* event, const std::string& sectionname)
    223     {
    224         event->registerEventListener(this, sectionname);
    225         this->events_.push_back(event);
    226     }
    227 
    228     void BaseObject::removeEvent(BaseObject* event)
    229     {
    230         this->events_.remove(event);
    231     }
    232 
    233     BaseObject* BaseObject::getEvent(unsigned int index) const
     208    /**
     209        @brief Adds a new event source for a specific state.
     210        @param source The object which sends events to this object
     211        @param state The state of this object which will be affected by the events
     212    */
     213    void BaseObject::addEventSource(BaseObject* source, const std::string& state)
     214    {
     215        this->eventSources_[source] = state;
     216        source->registerEventListener(this);
     217    }
     218
     219    /**
     220        @brief Removes an eventsource (but doesn't unregister itself at the source).
     221    */
     222    void BaseObject::removeEventSource(BaseObject* source)
     223    {
     224        this->eventSources_.erase(source);
     225        source->unregisterEventListener(this);
     226    }
     227
     228    /**
     229        @brief Returns an eventsource with a given index.
     230    */
     231    BaseObject* BaseObject::getEventSource(unsigned int index, const std::string& state) const
    234232    {
    235233        unsigned int i = 0;
    236         for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
    237         {
     234        for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); ++it)
     235        {
     236            if (it->second != state)
     237                continue;
     238           
    238239            if (i == index)
    239                 return (*it);
     240                return it->first;
    240241            ++i;
    241242        }
     
    243244    }
    244245
    245     void BaseObject::addEventContainer(const std::string& sectionname, EventContainer* container)
    246     {
    247         std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
    248         if (it != this->eventContainers_.end())
    249         {
    250             COUT(2) << "Warning: Overwriting EventContainer in class " << this->getIdentifier()->getName() << "." << std::endl;
     246    /**
     247        @brief Adds an object which listens to the events of this object. The events are sent to the other objects mainstate.
     248    */
     249    void BaseObject::addEventListener(BaseObject* listener)
     250    {
     251        this->eventListenersXML_.insert(listener);
     252        listener->addEventSource(this, "mainstate");
     253    }
     254   
     255    /**
     256        @brief Returns an event listener with a given index.
     257    */
     258    BaseObject* BaseObject::getEventListener(unsigned int index) const
     259    {
     260        unsigned int i = 0;
     261        for (std::set<BaseObject*>::const_iterator it = this->eventListenersXML_.begin(); it != this->eventListenersXML_.end(); ++it)
     262        {
     263            if (i == index)
     264                return *it;
     265            ++i;
     266        }
     267        return 0;
     268    }
     269
     270    /**
     271        @brief Adds a new event-state to the object. Event-states are states which can be changed by events.
     272        @param name  The name of the event
     273        @param state The object containing information about the event-state
     274    */
     275    void BaseObject::addEventState(const std::string& name, EventState* state)
     276    {
     277        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
     278        if (it != this->eventStates_.end())
     279        {
     280            COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << "." << std::endl;
    251281            delete (it->second);
    252282        }
    253283
    254         this->eventContainers_[sectionname] = container;
    255     }
    256 
    257     EventContainer* BaseObject::getEventContainer(const std::string& sectionname) const
    258     {
    259         std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
    260         if (it != this->eventContainers_.end())
     284        this->eventStates_[name] = state;
     285    }
     286
     287    /**
     288        @brief Returns the event-state with the given name.
     289    */
     290    EventState* BaseObject::getEventState(const std::string& name) const
     291    {
     292        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
     293        if (it != this->eventStates_.end())
    261294            return ((*it).second);
    262295        else
     
    264297    }
    265298
    266     void BaseObject::fireEvent()
    267     {
    268         this->fireEvent(true);
    269         this->fireEvent(false);
    270     }
    271 
    272     void BaseObject::fireEvent(bool activate)
    273     {
    274         this->fireEvent(activate, this);
    275     }
    276 
    277     void BaseObject::fireEvent(bool activate, BaseObject* originator)
    278     {
    279         Event event(activate, originator);
    280 
    281         for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
    282         {
    283             event.sectionname_ = it->second;
    284             it->first->processEvent(event);
    285         }
    286     }
    287 
     299    /**
     300        @brief Fires an event (without a state).
     301    */
     302    void BaseObject::fireEvent(const std::string& name)
     303    {
     304        this->fireEvent(true, name);
     305        this->fireEvent(false, name);
     306    }
     307
     308    /**
     309        @brief Fires an event which activates or deactivates a state.
     310    */
     311    void BaseObject::fireEvent(bool activate, const std::string& name)
     312    {
     313        this->fireEvent(activate, this, name);
     314    }
     315
     316    /**
     317        @brief Fires an event which activates or deactivates a state with agiven originator (the object which triggered the event).
     318    */
     319    void BaseObject::fireEvent(bool activate, BaseObject* originator, const std::string& name)
     320    {
     321        Event event(activate, originator, name);
     322
     323        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
     324        {
     325            event.statename_ = (*it)->eventSources_[this];
     326            (*it)->processEvent(event);
     327        }
     328    }
     329
     330    /**
     331        @brief Fires an event, using the Event struct.
     332    */
    288333    void BaseObject::fireEvent(Event& event)
    289334    {
    290         for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
    291             it->first->processEvent(event);
    292     }
    293 
     335        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
     336            (*it)->processEvent(event);
     337    }
     338
     339    /**
     340        @brief Processing an event by calling the right main state.
     341        @param event The event struct which contains the information about the event
     342    */
    294343    void BaseObject::processEvent(Event& event)
    295344    {
    296         ORXONOX_SET_EVENT(BaseObject, "activity", setActive, event);
    297         ORXONOX_SET_EVENT(BaseObject, "visibility", setVisible, event);
    298     }
    299 
    300     void BaseObject::setMainStateName(const std::string& name)
    301     {
    302         if (this->mainStateName_ != name)
    303         {
    304             this->mainStateName_ = name;
    305             if (this->functorSetMainState_)
    306                 delete this->functorSetMainState_;
    307             if (this->functorGetMainState_)
    308                 delete this->functorGetMainState_;
    309             this->changedMainState();
    310             if (!this->functorSetMainState_)
    311                 COUT(2) << "Warning: \"" << name << "\" is not a valid MainState." << std::endl;
    312         }
    313     }
    314 
     345        this->registerEventStates();
     346       
     347        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_);
     348        if (it != this->eventStates_.end())
     349            it->second->process(event, this);
     350        else if (event.statename_ != "")
     351            COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
     352        else
     353            COUT(2) << "Warning: Event with invalid source sent to object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
     354    }
     355
     356    /**
     357        @brief Sets the main state of the object to a given boolean value.
     358       
     359        Note: The main state of an object can be set with the @ref setMainStateName function.
     360        It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state,
     361        the main state is used by default).
     362    */
    315363    void BaseObject::setMainState(bool state)
    316364    {
    317         if (this->functorSetMainState_)
    318             (*this->functorSetMainState_)(state);
     365        if (this->mainStateFunctor_)
     366        {
     367            if (this->mainStateFunctor_->getParamCount() == 0)
     368            {
     369                if (state)
     370                    (*this->mainStateFunctor_)();
     371            }
     372            else
     373            {
     374                (*this->mainStateFunctor_)(state);
     375            }
     376        }
    319377        else
    320378            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
    321379    }
    322380
    323     bool BaseObject::getMainState() const
    324     {
    325         if (this->functorGetMainState_)
    326         {
    327             (*this->functorGetMainState_)();
    328             return this->functorGetMainState_->getReturnvalue();
    329         }
    330         else
    331         {
    332             COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
    333             return false;
    334         }
    335     }
    336 
    337     void BaseObject::changedMainState()
    338     {
    339         SetMainState(BaseObject, "activity",   setActive,  isActive);
    340         SetMainState(BaseObject, "visibility", setVisible, isVisible);
     381    /**
     382        @brief This function gets called if the main state name of the object changes.
     383    */
     384    void BaseObject::changedMainStateName()
     385    {
     386        this->mainStateFunctor_ = 0;
     387
     388        if (this->mainStateName_ != "")
     389        {
     390            this->registerEventStates();
     391           
     392            std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_);
     393            if (it != this->eventStates_.end() && it->second->getFunctor())
     394            {
     395                if (it->second->getFunctor()->getParamCount() <= 1)
     396                    this->mainStateFunctor_ = it->second->getFunctor();
     397                else
     398                    COUT(2) << "Warning: Can't use \"" << this->mainStateName_ << "\" as MainState because it needs a second argument." << std::endl;
     399            }
     400            else
     401                COUT(2) << "Warning: \"" << this->mainStateName_ << "\" is not a valid MainState." << std::endl;
     402        }
     403    }
     404   
     405    /**
     406        @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary.
     407    */
     408    void BaseObject::registerEventStates()
     409    {
     410        if (!this->bRegisteredEventStates_)
     411        {
     412            Element xmlelement;
     413            this->XMLEventPort(xmlelement, XMLPort::NOP);
     414        }
     415    }
     416   
     417    /**
     418        @brief Manually loads all event states, even if the class doesn't officially support them. This is needed by some classes like @ref EventDispatcher or @ref EventTarget.
     419    */
     420    void BaseObject::loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier)
     421    {
     422        Element* events = xmlelement.FirstChildElement("events", false);
     423        if (events)
     424        {
     425            // get the list of all states present
     426            std::list<std::string> eventnames;
     427            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
     428            {
     429                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
     430                    eventnames.push_back(child->Value());
     431            }
     432            else if (mode == XMLPort::SaveObject)
     433            {
     434            }
     435
     436            // iterate through all states and get the event sources
     437            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
     438            {
     439                std::string statename = (*it);
     440
     441                // if the event state is already known, continue with the next state
     442                orxonox::EventState* eventstate = object->getEventState(statename);
     443                if (eventstate)
     444                    continue;
     445
     446                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(identifier->getXMLPortObjectContainer(statename));
     447                if (!container)
     448                {
     449                    ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + "(" + statename + ")");
     450                    ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + "(" + statename + ")");
     451                    setfunctor->setDefaultValue(1, statename);
     452                    getfunctor->setDefaultValue(1, statename);
     453
     454                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(statename, identifier, setfunctor, getfunctor, false, true);
     455                    identifier->addXMLPortObjectContainer(statename, container);
     456                }
     457                container->port(object, *events, mode);
     458            }
     459        }
    341460    }
    342461}
  • code/trunk/src/libraries/core/BaseObject.h

    r5781 r5929  
    3737#define _BaseObject_H__
    3838
    39 #define SetMainState(classname, statename, setfunction, getfunction) \
    40     if (this->getMainStateName() == statename) \
    41     { \
    42         this->functorSetMainState_ = createFunctor(&classname::setfunction)->setObject(this); \
    43         this->functorGetMainState_ = createFunctor(&classname::getfunction)->setObject(this); \
    44     }
    45 
    46 
    4739#include "CorePrereqs.h"
    4840
     
    5345#include "OrxonoxClass.h"
    5446#include "Super.h"
     47#include "SmartPtr.h"
    5548
    5649namespace orxonox
     
    6861            virtual ~BaseObject();
    6962            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
     63            virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
    7064
    7165            /** @brief Returns if the object was initialized (passed the object registration). @return True was the object is initialized */
     
    110104
    111105            void setMainState(bool state);
    112             bool getMainState() const;
    113 
    114             void setMainStateName(const std::string& name);
     106
     107            /** @brief Sets the name of the main state (used for event reactions). */
     108            void setMainStateName(const std::string& name)
     109            {
     110                if (this->mainStateName_ != name)
     111                {
     112                    this->mainStateName_ = name;
     113                    this->changedMainStateName();
     114                }
     115            }
     116            /** @brief Returns the name of the main state. */
    115117            inline const std::string& getMainStateName() const { return this->mainStateName_; }
    116             virtual void changedMainState();
     118            /** @brief This function gets called if the main state name of the object changes. */
     119            virtual void changedMainStateName();
    117120
    118121            /** @brief Sets a pointer to the xml file that loaded this object. @param file The pointer to the XMLFile */
     
    134137            inline BaseObject* getCreator() const { return this->creator_; }
    135138
    136             inline void setScene(Scene* scene) { this->scene_ = scene; }
    137             inline Scene* getScene() const { return this->scene_; }
    138 
    139             inline void setGametype(Gametype* gametype)
     139            inline void setScene(const SmartPtr<Scene>& scene, uint32_t sceneID) { this->scene_ = scene; this->sceneID_=sceneID; }
     140            inline const SmartPtr<Scene>& getScene() const { return this->scene_; }
     141            inline virtual uint32_t getSceneID() const { return this->sceneID_; }
     142
     143            inline void setGametype(const SmartPtr<Gametype>& gametype)
    140144            {
    141145                if (gametype != this->gametype_)
     
    146150                }
    147151            }
    148             inline Gametype* getGametype() const { return this->gametype_; }
     152            inline const SmartPtr<Gametype>& getGametype() const { return this->gametype_; }
    149153            inline Gametype* getOldGametype() const { return this->oldGametype_; }
    150154            virtual void changedGametype() {}
    151155
    152             void fireEvent();
    153             void fireEvent(bool activate);
    154             void fireEvent(bool activate, BaseObject* originator);
     156            void addEventSource(BaseObject* source, const std::string& state);
     157            void removeEventSource(BaseObject* source);
     158            BaseObject* getEventSource(unsigned int index, const std::string& state) const;
     159           
     160            void addEventListener(BaseObject* listener);
     161            BaseObject* getEventListener(unsigned int index) const;
     162
     163            void fireEvent(const std::string& name = "");
     164            void fireEvent(bool activate, const std::string& name = "");
     165            void fireEvent(bool activate, BaseObject* originator, const std::string& name = "");
    155166            void fireEvent(Event& event);
    156167
    157168            virtual void processEvent(Event& event);
    158 
    159             inline void registerEventListener(BaseObject* object, const std::string& sectionname)
    160                 { this->eventListeners_[object] = sectionname; }
    161             inline void unregisterEventListener(BaseObject* object)
    162                 { this->eventListeners_.erase(object); }
    163 
    164             void addEvent(BaseObject* event, const std::string& sectionname);
    165             void removeEvent(BaseObject* event);
    166             BaseObject* getEvent(unsigned int index) const;
    167 
    168             void addEventContainer(const std::string& sectionname, EventContainer* container);
    169             EventContainer* getEventContainer(const std::string& sectionname) const;
    170169
    171170            /** @brief Sets the indentation of the debug output in the Loader. @param indentation The indentation */
     
    173172            /** @brief Returns the indentation of the debug output in the Loader. @return The indentation */
    174173            inline const std::string& getLoaderIndentation() const { return this->loaderIndentation_; }
     174           
     175            static void loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier);
    175176
    176177        protected:
     178            void addEventState(const std::string& name, EventState* container);
     179            EventState* getEventState(const std::string& name) const;
     180
    177181            std::string name_;                                 //!< The name of the object
    178182            std::string oldName_;                              //!< The old name of the object
     
    180184            mbool       bVisible_;                             //!< True = the object is visible
    181185            std::string mainStateName_;
    182             Functor*    functorSetMainState_;
    183             Functor*    functorGetMainState_;
     186            Functor*    mainStateFunctor_;
    184187
    185188        private:
     189            /** @brief Adds an object which listens to the events of this object. */
     190            inline void registerEventListener(BaseObject* object)
     191                { this->eventListeners_.insert(object); }
     192            /** @brief Removes an event listener from this object. */
     193            inline void unregisterEventListener(BaseObject* object)
     194                { this->eventListeners_.erase(object); }
     195
    186196            void setXMLName(const std::string& name);
    187197            Template* getTemplate(unsigned int index) const;
     198            void registerEventStates();
    188199
    189200            bool                   bInitialized_;              //!< True if the object was initialized (passed the object registration)
     
    194205            Namespace*             namespace_;
    195206            BaseObject*            creator_;
    196             Scene*                 scene_;
    197             Gametype*              gametype_;
     207            SmartPtr<Scene>        scene_;
     208            uint32_t               sceneID_;
     209            SmartPtr<Gametype>     gametype_;
    198210            Gametype*              oldGametype_;
    199211            std::set<Template*>    templates_;
    200             std::map<BaseObject*,  std::string> eventListeners_;
    201             std::list<BaseObject*> events_;
    202             std::map<std::string, EventContainer*> eventContainers_;
     212           
     213            std::map<BaseObject*, std::string>  eventSources_;           //!< List of objects which send events to this object, mapped to the state which they affect
     214            std::set<BaseObject*>               eventListeners_;         //!< List of objects which listen to the events of this object
     215            std::set<BaseObject*>               eventListenersXML_;      //!< List of objects which listen to the events of this object through the "eventlisteners" subsection in XML
     216            std::map<std::string, EventState*>  eventStates_;            //!< Maps the name of the event states to their helper objects
     217            bool                                bRegisteredEventStates_; //!< Becomes true after the object registered its event states (with XMLEventPort)
    203218    };
    204219
     
    206221    SUPER_FUNCTION(2, BaseObject, changedActivity, false);
    207222    SUPER_FUNCTION(3, BaseObject, changedVisibility, false);
    208     SUPER_FUNCTION(4, BaseObject, processEvent, false);
    209     SUPER_FUNCTION(6, BaseObject, changedMainState, false);
    210     SUPER_FUNCTION(9, BaseObject, changedName, false);
    211     SUPER_FUNCTION(10, BaseObject, changedGametype, false);
     223    SUPER_FUNCTION(4, BaseObject, XMLEventPort, false);
     224    SUPER_FUNCTION(8, BaseObject, changedName, false);
     225    SUPER_FUNCTION(9, BaseObject, changedGametype, false);
    212226}
    213227
  • code/trunk/src/libraries/core/CMakeLists.txt

    r5781 r5929  
    1919
    2020SET_SOURCE_FILES(CORE_SRC_FILES
    21   Clock.cc
    22   ConfigFileManager.cc
    2321  ConfigValueContainer.cc
    2422  Core.cc
     
    3331  Language.cc
    3432  LuaState.cc
    35   MemoryArchive.cc
    3633  ObjectListBase.cc
    3734  OrxonoxClass.cc
    3835  Resource.cc
     36  ScopedSingletonManager.cc
    3937  WindowEventListener.cc
    4038
    4139  # command
    42   ArgumentCompletionFunctions.cc
    4340  CommandEvaluation.cc
    4441  CommandExecutor.cc
     
    4946
    5047  # hierarchy
    51   Factory.cc
    5248  Identifier.cc
    5349  MetaObjectList.cc
     
    6763  Shell.cc
    6864  TclBind.cc
     65
     66COMPILATION_BEGIN FilesystemCompilation.cc
     67  ArgumentCompletionFunctions.cc
     68  ConfigFileManager.cc
     69  MemoryArchive.cc
     70  PathConfig.cc
     71COMPILATION_END
     72
     73  # multithreading
     74  ThreadPool.cc
     75COMPILATION_BEGIN ThreadCompilation.cc
    6976  TclThreadManager.cc
    70  
    71   # multithreading
    7277  Thread.cc
    73   ThreadPool.cc
     78COMPILATION_END
    7479)
     80
    7581ADD_SUBDIRECTORY(input)
    7682
  • code/trunk/src/libraries/core/ClassFactory.h

    r5781 r5929  
    4242
    4343#include "util/Debug.h"
    44 #include "Factory.h"
    4544#include "Identifier.h"
    4645
    4746namespace orxonox
    4847{
     48    // ###########################
     49    // ###       Factory       ###
     50    // ###########################
     51    //! Base-class of ClassFactory.
     52    class _CoreExport Factory
     53    {
     54        public:
     55            virtual ~Factory() {};
     56            virtual BaseObject* fabricate(BaseObject* creator) = 0;
     57    };
     58
    4959    // ###############################
    5060    // ###      ClassFactory       ###
     
    5262    //! The ClassFactory is able to create new objects of a specific class.
    5363    template <class T>
    54     class ClassFactory : public BaseFactory
     64    class ClassFactory : public Factory
    5565    {
    5666        public:
    57             static bool create(const std::string& name, bool bLoadable = true);
    58             BaseObject* fabricate(BaseObject* creator);
     67            /**
     68                @brief Constructor: Adds the ClassFactory to the Identifier of the same type.
     69                @param name The name of the class
     70                @param bLoadable True if the class can be loaded through XML
     71            */
     72            ClassFactory(const std::string& name, bool bLoadable = true)
     73            {
     74                COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
     75                ClassIdentifier<T>::getIdentifier(name)->addFactory(this);
     76                ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
     77            }
    5978
    60         private:
    61             ClassFactory() {}                               // Don't create
    62             ClassFactory(const ClassFactory& factory) {}    // Don't copy
    63             virtual ~ClassFactory() {}                      // Don't delete
    64 
    65             static T* createNewObject(BaseObject* creator);
     79            /**
     80                @brief Creates and returns a new object of class T.
     81                @return The new object
     82            */
     83            inline BaseObject* fabricate(BaseObject* creator)
     84            {
     85                return static_cast<BaseObject*>(new T(creator));
     86            }
    6687    };
    67 
    68     /**
    69         @brief Adds the ClassFactory to the Identifier of the same type and the Identifier to the Factory.
    70         @param name The name of the class
    71         @param bLoadable True if the class can be loaded through XML
    72         @return Always true (this is needed because the compiler only allows assignments before main())
    73     */
    74     template <class T>
    75     bool ClassFactory<T>::create(const std::string& name, bool bLoadable)
    76     {
    77         COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
    78         ClassIdentifier<T>::getIdentifier(name)->addFactory(new ClassFactory<T>);
    79         ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
    80         Factory::add(name, ClassIdentifier<T>::getIdentifier());
    81 
    82         return true;
    83     }
    84 
    85     /**
    86         @brief Creates and returns a new object of class T.
    87         @return The new object
    88     */
    89     template <class T>
    90     inline BaseObject* ClassFactory<T>::fabricate(BaseObject* creator)
    91     {
    92         return ClassFactory<T>::createNewObject(creator);
    93     }
    94 
    95     /**
    96         @brief Creates and returns a new object of class T; this is a wrapper for the new operator.
    97         @return The new object
    98     */
    99     template <class T>
    100     inline T* ClassFactory<T>::createNewObject(BaseObject* creator)
    101     {
    102         return new T(creator);
    103     }
    10488}
    10589
  • code/trunk/src/libraries/core/ClassTreeMask.cc

    r5781 r5929  
    488488
    489489                // Remove the redundant subnode from the current node
     490                delete (*it);
    490491                node->subnodes_.erase(it++);
    491492            }
  • code/trunk/src/libraries/core/ClassTreeMask.h

    r5781 r5929  
    265265
    266266            /** @brief Returns true if the ClassTreeMaskObjectIterator points at the given object. @param pointer The pointer of the object */
    267             inline bool operator==(BaseObject* pointer) const { return ((*this->objectIterator_) == pointer); }
     267            inline bool operator==(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) == pointer) || (!this->objectIterator_ && pointer == 0); }
    268268            /** @brief Returns true if the ClassTreeMaskObjectIterator doesn't point at the given object. @param pointer The pointer of the object */
    269             inline bool operator!=(BaseObject* pointer) const { return ((*this->objectIterator_) != pointer); }
     269            inline bool operator!=(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) != pointer) || (!this->objectIterator_ && pointer != 0); }
    270270            /** @brief Returns true if the ClassTreeMaskObjectIterator hasn't already reached the end. */
    271271            inline operator bool() const { return (this->objectIterator_); }
  • code/trunk/src/libraries/core/CommandExecutor.cc

    r5781 r5929  
    468468        CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear();
    469469        std::string lowercase = getLowercase(fragment);
    470         for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMapBegin(); it != Identifier::getLowercaseIdentifierMapEnd(); ++it)
     470        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapBegin(); it != Identifier::getLowercaseStringIdentifierMapEnd(); ++it)
    471471            if ((*it).second->hasConsoleCommands())
    472472                if ((*it).first.find(lowercase) == 0 || fragment == "")
     
    516516    {
    517517        std::string lowercase = getLowercase(name);
    518         std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMap().find(lowercase);
    519         if ((it != Identifier::getLowercaseIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
     518        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMap().find(lowercase);
     519        if ((it != Identifier::getLowercaseStringIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
    520520            return (*it).second;
    521521
  • code/trunk/src/libraries/core/CommandLine.cc

    r5738 r5929  
    3131#include <algorithm>
    3232#include <sstream>
    33 #include <boost/filesystem.hpp>
    3433
    3534#include "util/Convert.h"
     
    3837#include "util/StringUtils.h"
    3938#include "util/SubString.h"
    40 #include "Core.h"
     39#include "PathConfig.h"
    4140
    4241namespace orxonox
     
    285284        }
    286285
     286        infoStr << std::endl;
    287287        infoStr << "Usage: orxonox [options]" << std::endl;
    288288        infoStr << "Available options:" << std::endl;
     
    348348    {
    349349        std::string filename = CommandLine::getValue("optionsFile").getString();
    350         boost::filesystem::path filepath(Core::getConfigPath() / filename);
    351350
    352351        // look for additional arguments in given file or start.ini as default
    353352        // They will not overwrite the arguments given directly
    354353        std::ifstream file;
    355         file.open(filepath.string().c_str());
     354        file.open((PathConfig::getConfigPathString() + filename).c_str());
    356355        std::vector<std::string> args;
    357356        if (file)
  • code/trunk/src/libraries/core/ConfigFileManager.cc

    r5781 r5929  
    3636#include "ConsoleCommand.h"
    3737#include "ConfigValueContainer.h"
    38 #include "Core.h"
     38#include "PathConfig.h"
    3939
    4040namespace orxonox
     
    4848    bool config(const std::string& classname, const std::string& varname, const std::string& value)
    4949    {
    50         std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
    51         if (identifier != Identifier::getLowercaseIdentifierMapEnd())
     50        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
     51        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
    5252        {
    5353            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
     
    6060    bool tconfig(const std::string& classname, const std::string& varname, const std::string& value)
    6161    {
    62         std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
    63         if (identifier != Identifier::getLowercaseIdentifierMapEnd())
     62        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
     63        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
    6464        {
    6565            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
     
    222222
    223223        // Get default file if necessary and available
    224         boost::filesystem::path filepath(Core::getConfigPath() / this->filename_);
     224        boost::filesystem::path filepath(PathConfig::getConfigPath() / this->filename_);
    225225        if (!boost::filesystem::exists(filepath))
    226226        {
    227227            // Try to get default one from the data folder
    228             boost::filesystem::path defaultFilepath(Core::getDataPath() / "defaultConfig" / this->filename_);
     228            boost::filesystem::path defaultFilepath(PathConfig::getDataPath() / "defaultConfig" / this->filename_);
    229229            if (boost::filesystem::exists(defaultFilepath))
    230230            {
     
    336336    {
    337337        std::ofstream file;
    338         file.open((Core::getConfigPathString() + filename_).c_str(), std::fstream::out);
     338        file.open((PathConfig::getConfigPathString() + filename_).c_str(), std::fstream::out);
    339339        file.setf(std::ios::fixed, std::ios::floatfield);
    340340        file.precision(6);
     
    376376        for (std::list<ConfigFileSection*>::iterator it1 = this->sections_.begin(); it1 != this->sections_.end(); )
    377377        {
    378             std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getIdentifierMap().find((*it1)->getName());
    379             if (it2 != Identifier::getIdentifierMapEnd() && (*it2).second->hasConfigValues())
     378            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getStringIdentifierMap().find((*it1)->getName());
     379            if (it2 != Identifier::getStringIdentifierMapEnd() && (*it2).second->hasConfigValues())
    380380            {
    381381                // The section exists, delete comment
     
    455455        if (this->type_ == ConfigFileType::Settings)
    456456        {
    457             for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
     457            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
    458458            {
    459459                if (it->second->hasConfigValues())
  • code/trunk/src/libraries/core/Core.cc

    r5781 r5929  
    3737
    3838#include <cassert>
    39 #include <fstream>
    40 #include <cstdlib>
    41 #include <cstdio>
    42 #include <boost/version.hpp>
    43 #include <boost/filesystem.hpp>
     39#include <vector>
    4440
    4541#ifdef ORXONOX_PLATFORM_WINDOWS
     
    5046#  undef min
    5147#  undef max
    52 #elif defined(ORXONOX_PLATFORM_APPLE)
    53 #  include <sys/param.h>
    54 #  include <mach-o/dyld.h>
    55 #else /* Linux */
    56 #  include <sys/types.h>
    57 #  include <unistd.h>
    5848#endif
    5949
    60 #include "SpecialConfig.h"
     50#include "util/Clock.h"
    6151#include "util/Debug.h"
    6252#include "util/Exception.h"
    6353#include "util/SignalHandler.h"
    64 #include "Clock.h"
     54#include "PathConfig.h"
    6555#include "CommandExecutor.h"
    6656#include "CommandLine.h"
     
    6959#include "CoreIncludes.h"
    7060#include "DynLibManager.h"
    71 #include "Factory.h"
    7261#include "GameMode.h"
    7362#include "GraphicsManager.h"
     
    7665#include "Language.h"
    7766#include "LuaState.h"
     67#include "ScopedSingletonManager.h"
    7868#include "Shell.h"
    7969#include "TclBind.h"
     
    8171#include "input/InputManager.h"
    8272
    83 // Boost 1.36 has some issues with deprecated functions that have been omitted
    84 #if (BOOST_VERSION == 103600)
    85 #  define BOOST_LEAF_FUNCTION filename
    86 #else
    87 #  define BOOST_LEAF_FUNCTION leaf
    88 #endif
    89 
    9073namespace orxonox
    9174{
     
    9376    Core* Core::singletonPtr_s  = 0;
    9477
    95     SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
    96     SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
    9778    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
    9879#ifdef ORXONOX_PLATFORM_WINDOWS
     
    11798            RegisterRootObject(CoreConfiguration);
    11899            this->setConfigValues();
    119 
    120             // External data directory only exists for dev runs
    121             if (Core::isDevelopmentRun())
    122             {
    123                 // Possible data path override by the command line
    124                 if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
    125                     tsetExternalDataPath(CommandLine::getValue("externalDataPath"));
    126             }
    127100        }
    128101
     
    194167        }
    195168
    196         /**
    197         @brief
    198             Temporary sets the external data path
    199         @param path
    200             The new data path
    201         */
    202         void tsetExternalDataPath(const std::string& path)
    203         {
    204             externalDataPath_ = boost::filesystem::path(path);
    205         }
    206 
    207169        void initializeRandomNumberGenerator()
    208170        {
     
    222184        std::string language_;                          //!< The language
    223185        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
    224 
    225         //! Path to the parent directory of the ones above if program was installed with relativ pahts
    226         boost::filesystem::path rootPath_;
    227         boost::filesystem::path executablePath_;        //!< Path to the executable
    228         boost::filesystem::path modulePath_;            //!< Path to the modules
    229         boost::filesystem::path dataPath_;              //!< Path to the data file folder
    230         boost::filesystem::path externalDataPath_;      //!< Path to the external data file folder
    231         boost::filesystem::path configPath_;            //!< Path to the config file folder
    232         boost::filesystem::path logPath_;               //!< Path to the log file folder
    233186    };
    234187
     
    240193        , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
    241194        , configuration_(new CoreConfiguration()) // Don't yet create config values!
    242         , bDevRun_(false)
    243195        , bGraphicsLoaded_(false)
    244196    {
    245197        // Set the hard coded fixed paths
    246         this->setFixedPaths();
     198        this->pathConfig_.reset(new PathConfig());
    247199
    248200        // Create a new dynamic library manager
     
    250202
    251203        // Load modules
    252         try
    253         {
    254             // We search for helper files with the following extension
    255             std::string moduleextension = specialConfig::moduleExtension;
    256             size_t moduleextensionlength = moduleextension.size();
    257 
    258             // Search in the directory of our executable
    259             boost::filesystem::path searchpath = this->configuration_->modulePath_;
    260 
    261             // Add that path to the PATH variable in case a module depends on another one
    262             std::string pathVariable = getenv("PATH");
    263             putenv(const_cast<char*>(("PATH=" + pathVariable + ";" + configuration_->modulePath_.string()).c_str()));
    264 
    265             boost::filesystem::directory_iterator file(searchpath);
    266             boost::filesystem::directory_iterator end;
    267 
    268             // Iterate through all files
    269             while (file != end)
     204        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
     205        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
     206        {
     207            try
    270208            {
    271                 std::string filename = file->BOOST_LEAF_FUNCTION();
    272 
    273                 // Check if the file ends with the exension in question
    274                 if (filename.size() > moduleextensionlength)
    275                 {
    276                     if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
    277                     {
    278                         // We've found a helper file - now load the library with the same name
    279                         std::string library = filename.substr(0, filename.size() - moduleextensionlength);
    280                         boost::filesystem::path librarypath = searchpath / library;
    281 
    282                         try
    283                         {
    284                             DynLibManager::getInstance().load(librarypath.string());
    285                         }
    286                         catch (...)
    287                         {
    288                             COUT(1) << "Couldn't load module \"" << librarypath.string() << "\": " << Exception::handleMessage() << std::endl;
    289                         }
    290                     }
    291                 }
    292 
    293                 ++file;
     209                this->dynLibManager_->load(*it);
    294210            }
    295         }
    296         catch (...)
    297         {
    298             COUT(1) << "An error occurred while loading modules: " << Exception::handleMessage() << std::endl;
     211            catch (...)
     212            {
     213                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
     214            }
    299215        }
    300216
     
    303219
    304220        // Set configurable paths like log, config and media
    305         this->setConfigurablePaths();
     221        this->pathConfig_->setConfigurablePaths();
    306222
    307223        // create a signal handler (only active for linux)
    308224        // This call is placed as soon as possible, but after the directories are set
    309225        this->signalHandler_.reset(new SignalHandler());
    310         this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
     226        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
    311227
    312228        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
    313         OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
     229        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
    314230
    315231        // Parse additional options file now that we know its path
     
    334250
    335251        // creates the class hierarchy for all classes with factories
    336         Factory::createClassHierarchy();
     252        Identifier::createClassHierarchy();
    337253
    338254        // Do this soon after the ConfigFileManager has been created to open up the
     
    344260
    345261        // initialise Tcl
    346         this->tclBind_.reset(new TclBind(Core::getDataPathString()));
     262        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
    347263        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
    348264
    349265        // create a shell
    350266        this->shell_.reset(new Shell());
     267
     268        // Create singletons that always exist (in other libraries)
     269        this->rootScope_.reset(new Scope<ScopeID::Root>());
    351270    }
    352271
     
    370289        inputManager_.reset(new InputManager());
    371290
    372         // load the CEGUI interface
     291        // Load the CEGUI interface
    373292        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
    374293            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
    375294
     295        bGraphicsLoaded_ = true;
     296        GameMode::bShowsGraphics_s = true;
     297
     298        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
     299        graphicsManager_->loadDebugOverlay();
     300
     301        // Create singletons associated with graphics (in other libraries)
     302        graphicsScope_.reset(new Scope<ScopeID::Graphics>());
     303
    376304        unloader.Dismiss();
    377 
    378         bGraphicsLoaded_ = true;
    379305    }
    380306
    381307    void Core::unloadGraphics()
    382308    {
    383         this->guiManager_.reset();;
    384         this->inputManager_.reset();;
     309        this->graphicsScope_.reset();
     310        this->guiManager_.reset();
     311        this->inputManager_.reset();
    385312        this->graphicsManager_.reset();
    386313
     
    397324
    398325        bGraphicsLoaded_ = false;
     326        GameMode::bShowsGraphics_s = false;
    399327    }
    400328
     
    457385    }
    458386
    459     /*static*/ void Core::tsetExternalDataPath(const std::string& path)
    460     {
    461         getInstance().configuration_->tsetExternalDataPath(path);
    462     }
    463 
    464     /*static*/ const boost::filesystem::path& Core::getDataPath()
    465     {
    466         return getInstance().configuration_->dataPath_;
    467     }
    468     /*static*/ std::string Core::getDataPathString()
    469     {
    470         return getInstance().configuration_->dataPath_.string() + '/';
    471     }
    472 
    473     /*static*/ const boost::filesystem::path& Core::getExternalDataPath()
    474     {
    475         return getInstance().configuration_->externalDataPath_;
    476     }
    477     /*static*/ std::string Core::getExternalDataPathString()
    478     {
    479         return getInstance().configuration_->externalDataPath_.string() + '/';
    480     }
    481 
    482     /*static*/ const boost::filesystem::path& Core::getConfigPath()
    483     {
    484         return getInstance().configuration_->configPath_;
    485     }
    486     /*static*/ std::string Core::getConfigPathString()
    487     {
    488         return getInstance().configuration_->configPath_.string() + '/';
    489     }
    490 
    491     /*static*/ const boost::filesystem::path& Core::getLogPath()
    492     {
    493         return getInstance().configuration_->logPath_;
    494     }
    495     /*static*/ std::string Core::getLogPathString()
    496     {
    497         return getInstance().configuration_->logPath_.string() + '/';
    498     }
    499 
    500     /*static*/ const boost::filesystem::path& Core::getRootPath()
    501     {
    502         return getInstance().configuration_->rootPath_;
    503     }
    504     /*static*/ std::string Core::getRootPathString()
    505     {
    506         return getInstance().configuration_->rootPath_.string() + '/';
    507     }
    508 
    509387    /**
    510388    @note
     
    553431    }
    554432
    555     /**
    556     @brief
    557         Retrievs the executable path and sets all hard coded fixed path (currently only the module path)
    558         Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
    559         If found it means that this is not an installed run, hence we
    560         don't write the logs and config files to ~/.orxonox
    561     @throw
    562         GeneralException
    563     */
    564     void Core::setFixedPaths()
    565     {
    566         //////////////////////////
    567         // FIND EXECUTABLE PATH //
    568         //////////////////////////
    569 
    570 #ifdef ORXONOX_PLATFORM_WINDOWS
    571         // get executable module
    572         TCHAR buffer[1024];
    573         if (GetModuleFileName(NULL, buffer, 1024) == 0)
    574             ThrowException(General, "Could not retrieve executable path.");
    575 
    576 #elif defined(ORXONOX_PLATFORM_APPLE)
    577         char buffer[1024];
    578         unsigned long path_len = 1023;
    579         if (_NSGetExecutablePath(buffer, &path_len))
    580             ThrowException(General, "Could not retrieve executable path.");
    581 
    582 #else /* Linux */
    583         /* written by Nicolai Haehnle <prefect_@gmx.net> */
    584 
    585         /* Get our PID and build the name of the link in /proc */
    586         char linkname[64]; /* /proc/<pid>/exe */
    587         if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
    588         {
    589             /* This should only happen on large word systems. I'm not sure
    590                what the proper response is here.
    591                Since it really is an assert-like condition, aborting the
    592                program seems to be in order. */
    593             assert(false);
    594         }
    595 
    596         /* Now read the symbolic link */
    597         char buffer[1024];
    598         int ret;
    599         ret = readlink(linkname, buffer, 1024);
    600         /* In case of an error, leave the handling up to the caller */
    601         if (ret == -1)
    602             ThrowException(General, "Could not retrieve executable path.");
    603 
    604         /* Ensure proper NUL termination */
    605         buffer[ret] = 0;
    606 #endif
    607 
    608         configuration_->executablePath_ = boost::filesystem::path(buffer);
    609 #ifndef ORXONOX_PLATFORM_APPLE
    610         configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
    611 #endif
    612 
    613         /////////////////////
    614         // SET MODULE PATH //
    615         /////////////////////
    616 
    617         if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
    618         {
    619             COUT(1) << "Running from the build tree." << std::endl;
    620             Core::bDevRun_ = true;
    621             configuration_->modulePath_ = specialConfig::moduleDevDirectory;
    622         }
    623         else
    624         {
    625 
    626 #ifdef INSTALL_COPYABLE // --> relative paths
    627 
    628             // Also set the root path
    629             boost::filesystem::path relativeExecutablePath(specialConfig::defaultRuntimePath);
    630             configuration_->rootPath_ = configuration_->executablePath_;
    631             while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
    632                    && !configuration_->rootPath_.empty())
    633                 configuration_->rootPath_ = configuration_->rootPath_.branch_path();
    634             if (configuration_->rootPath_.empty())
    635                 ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
    636 
    637             // Module path is fixed as well
    638             configuration_->modulePath_ = configuration_->rootPath_ / specialConfig::defaultModulePath;
    639 
    640 #else
    641 
    642             // There is no root path, so don't set it at all
    643             // Module path is fixed as well
    644             configuration_->modulePath_ = specialConfig::moduleInstallDirectory;
    645 
    646 #endif
    647         }
    648     }
    649 
    650     /**
    651     @brief
    652         Sets config, log and media path and creates folders if necessary.
    653     @throws
    654         GeneralException
    655     */
    656     void Core::setConfigurablePaths()
    657     {
    658         if (Core::isDevelopmentRun())
    659         {
    660             configuration_->dataPath_  = specialConfig::dataDevDirectory;
    661             configuration_->externalDataPath_ = specialConfig::externalDataDevDirectory;
    662             configuration_->configPath_ = specialConfig::configDevDirectory;
    663             configuration_->logPath_    = specialConfig::logDevDirectory;
    664         }
    665         else
    666         {
    667 
    668 #ifdef INSTALL_COPYABLE // --> relative paths
    669 
    670             // Using paths relative to the install prefix, complete them
    671             configuration_->dataPath_   = configuration_->rootPath_ / specialConfig::defaultDataPath;
    672             configuration_->configPath_ = configuration_->rootPath_ / specialConfig::defaultConfigPath;
    673             configuration_->logPath_    = configuration_->rootPath_ / specialConfig::defaultLogPath;
    674 
    675 #else
    676 
    677             configuration_->dataPath_  = specialConfig::dataInstallDirectory;
    678 
    679             // Get user directory
    680 #  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
    681             char* userDataPathPtr(getenv("HOME"));
    682 #  else
    683             char* userDataPathPtr(getenv("APPDATA"));
    684 #  endif
    685             if (userDataPathPtr == NULL)
    686                 ThrowException(General, "Could not retrieve user data path.");
    687             boost::filesystem::path userDataPath(userDataPathPtr);
    688             userDataPath /= ".orxonox";
    689 
    690             configuration_->configPath_ = userDataPath / specialConfig::defaultConfigPath;
    691             configuration_->logPath_    = userDataPath / specialConfig::defaultLogPath;
    692 
    693 #endif
    694 
    695         }
    696 
    697         // Option to put all the config and log files in a separate folder
    698         if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
    699         {
    700             std::string directory(CommandLine::getValue("writingPathSuffix").getString());
    701             configuration_->configPath_ = configuration_->configPath_ / directory;
    702             configuration_->logPath_    = configuration_->logPath_    / directory;
    703         }
    704 
    705         // Create directories to avoid problems when opening files in non existent folders.
    706         std::vector<std::pair<boost::filesystem::path, std::string> > directories;
    707         directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
    708         directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
    709 
    710         for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
    711             it != directories.end(); ++it)
    712         {
    713             if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
    714             {
    715                 ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
    716                                          Please remove " + it->first.string());
    717             }
    718             if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
    719             {
    720                 COUT(4) << "Created " << it->second << " directory" << std::endl;
    721             }
    722         }
    723     }
    724 
    725433    void Core::preUpdate(const Clock& time)
    726434    {
     435        // singletons from other libraries
     436        ScopedSingletonManager::update<ScopeID::Root>(time);
    727437        if (this->bGraphicsLoaded_)
    728438        {
     
    731441            // process gui events
    732442            this->guiManager_->update(time);
     443            // graphics singletons from other libraries
     444            ScopedSingletonManager::update<ScopeID::Graphics>(time);
    733445        }
    734446        // process thread commands
  • code/trunk/src/libraries/core/Core.h

    r5781 r5929  
    2828 */
    2929
    30 /**
    31 @file
    32 @brief
    33     Declaration of the Core class.
    34 @details
    35     The Core class is a singleton, only used to configure some variables
    36     in the core through the config-file.
    37 */
    38 
    3930#ifndef _Core_H__
    4031#define _Core_H__
     
    4536#include <boost/scoped_ptr.hpp>
    4637#include "util/OutputHandler.h"
     38#include "util/Scope.h"
    4739#include "util/ScopeGuard.h"
    4840#include "util/Singleton.h"
     
    5547    @brief
    5648        The Core class is a singleton used to configure the program basics.
    57     @details
    58         The class provides information about the data, config and log path.
    59         It determines those by the use of platform specific functions.
    6049    @remark
    6150        You should only create this singleton once because it destroys the identifiers!
     
    8574            static void  resetLanguage();
    8675
    87             static void tsetExternalDataPath(const std::string& path);
    88             //! Returns the path to the data files as boost::filesystem::path
    89             static const boost::filesystem::path& getDataPath();
    90             //! Returns the path to the external data files as boost::filesystem::path
    91             static const boost::filesystem::path& getExternalDataPath();
    92             //! Returns the path to the config files as boost::filesystem::path
    93             static const boost::filesystem::path& getConfigPath();
    94             //! Returns the path to the log files as boost::filesystem::path
    95             static const boost::filesystem::path& getLogPath();
    96             //! Returns the path to the root folder as boost::filesystem::path
    97             static const boost::filesystem::path& getRootPath();
    98             //! Returns the path to the data files as std::string
    99             static std::string getDataPathString();
    100             //! Returns the path to the external data files as std::string
    101             static std::string getExternalDataPathString();
    102             //! Returns the path to the config files as std::string
    103             static std::string getConfigPathString();
    104             //! Returns the path to the log files as std::string
    105             static std::string getLogPathString();
    106             //! Returns the path to the root folder as std::string
    107             static std::string getRootPathString();
    108 
    109             static bool isDevelopmentRun() { return getInstance().bDevRun_; }
    110 
    11176        private:
    11277            Core(const Core&); //!< Don't use (undefined symbol)
     
    11883            void unloadGraphics();
    11984
    120             void setFixedPaths();
    121             void setConfigurablePaths();
    12285            void setThreadAffinity(int limitToCPU);
    12386
    12487            // Mind the order for the destruction!
     88            scoped_ptr<PathConfig>        pathConfig_;
    12589            scoped_ptr<DynLibManager>     dynLibManager_;
    12690            scoped_ptr<SignalHandler>     signalHandler_;
     
    137101            scoped_ptr<InputManager>      inputManager_;        //!< Interface to OIS
    138102            scoped_ptr<GUIManager>        guiManager_;          //!< Interface to GUI
     103            scoped_ptr<Scope<ScopeID::Root> >     rootScope_;
     104            scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_;
    139105
    140             bool                          bDevRun_;             //!< True for runs in the build directory (not installed)
    141106            bool                          bGraphicsLoaded_;
    142 
    143107            static Core* singletonPtr_s;
    144108    };
  • code/trunk/src/libraries/core/CoreIncludes.h

    r5781 r5929  
    2929/**
    3030    @file
    31     @brief Definition of macros for Identifier and Factory.
     31    @brief Definition of macros for Identifiers
    3232
    3333    Every class needs the RegisterObject(class) macro in its constructor. If the class is an interface
     
    4545#include "util/Debug.h"
    4646#include "Identifier.h"
    47 #include "Factory.h"
     47#include "SubclassIdentifier.h"
    4848#include "ClassFactory.h"
    4949#include "ObjectList.h"
     
    7676
    7777/**
    78     @brief Creates the entry in the Factory.
     78    @brief Creates the Factory.
    7979    @param ClassName The name of the class
    8080*/
    8181#define CreateFactory(ClassName) \
    82     bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, true)
     82    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, true)
    8383
    8484/**
    85     @brief Creates the entry in the Factory for classes which should not be loaded through XML.
     85    @brief Creates the Factory for classes which should not be loaded through XML.
    8686    @param ClassName The name of the class
    8787*/
    8888#define CreateUnloadableFactory(ClassName) \
    89     bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, false)
     89    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, false)
    9090
    9191/**
     
    100100{
    101101    /**
    102         @brief Returns the Identifier with a given name through the factory.
     102        @brief Returns the Identifier with a given name.
    103103        @param String The name of the class
    104104    */
    105105    inline Identifier* ClassByString(const std::string& name)
    106106    {
    107         return Factory::getIdentifier(name);
     107        return Identifier::getIdentifierByString(name);
    108108    }
    109109
    110110    /**
    111         @brief Returns the Identifier with a given network ID through the factory.
     111        @brief Returns the Identifier with a given lowercase name.
     112        @param String The lowercase name of the class
     113    */
     114    inline Identifier* ClassByLowercaseString(const std::string& name)
     115    {
     116        return Identifier::getIdentifierByLowercaseString(name);
     117    }
     118
     119    /**
     120        @brief Returns the Identifier with a given network ID.
    112121        @param networkID The network ID of the class
    113122    */
    114123    inline Identifier* ClassByID(uint32_t id)
    115124    {
    116         return Factory::getIdentifier(id);
     125        return Identifier::getIdentifierByID(id);
    117126    }
    118127}
  • code/trunk/src/libraries/core/CorePrereqs.h

    r5738 r5929  
    2828
    2929/**
    30   @file
    31   @brief Contains all the necessary forward declarations for all classes and structs.
     30@file
     31@brief
     32    Shared library macros, enums, constants and forward declarations for the core library
    3233*/
    3334
     
    4041// Shared library settings
    4142//-----------------------------------------------------------------------
     43
    4244#if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( CORE_STATIC_BUILD )
    4345#  ifdef CORE_SHARED_BUILD
     
    5658#endif
    5759
    58 
    59 //-----------------------------------------------------------------------
    60 // Forward declarations
    61 //-----------------------------------------------------------------------
     60//-----------------------------------------------------------------------
     61// Constants
     62//-----------------------------------------------------------------------
     63
     64namespace orxonox
     65{
     66    static const uint32_t OBJECTID_UNKNOWN = static_cast<uint32_t>(-1);
     67}
     68
     69//-----------------------------------------------------------------------
     70// Enums
     71//-----------------------------------------------------------------------
     72
    6273namespace orxonox
    6374{
     
    6677        enum Mode
    6778        {
     79            NOP,
    6880            LoadObject,
    6981            SaveObject,
     
    8294        };
    8395    };
    84 
     96}
     97
     98//-----------------------------------------------------------------------
     99// Forward declarations
     100//-----------------------------------------------------------------------
     101
     102namespace orxonox
     103{
    85104    typedef std::string LanguageEntryLabel;
    86105
    87106    class ArgumentCompleter;
    88107    class ArgumentCompletionListElement;
    89     class BaseFactory;
    90     class BaseMetaObjectListElement;
    91108    class BaseObject;
    92109    template <class T>
     
    98115    class ClassTreeMaskNode;
    99116    class ClassTreeMaskObjectIterator;
    100     class Clock;
    101117    class CommandEvaluation;
    102     class CommandExecutor;
    103118    class CommandLine;
    104119    class CommandLineArgument;
     
    109124    class ConfigFileManager;
    110125    class ConfigFileSection;
     126    struct ConfigFileType;
    111127    class ConfigValueContainer;
    112128    class ConsoleCommand;
     
    115131    class DynLibManager;
    116132    struct Event;
    117     class EventContainer;
     133    class EventState;
    118134    class Executor;
    119135    template <class T>
     
    125141    class FunctorMember;
    126142    class FunctorStatic;
     143    class Game;
     144    class GameState;
     145    struct GameStateInfo;
     146    struct GameStateTreeNode;
    127147    class GraphicsManager;
    128148    class GUIManager;
     
    131151    template <class T>
    132152    class Iterator;
    133     class IteratorBase;
    134153    class Language;
    135     class LanguageEntry;
    136     class Loader;
    137154    class LuaState;
    138155    class MemoryArchive;
     
    152169    class OgreWindowEventListener;
    153170    class OrxonoxClass;
     171    class PathConfig;
    154172    struct ResourceInfo;
    155173    class Shell;
    156174    class ShellListener;
    157175    template <class T>
     176    class SmartPtr;
     177    template <class T>
    158178    class SubclassIdentifier;
    159179    class TclBind;
     
    163183    class TclThreadManager;
    164184    class Template;
     185    class Thread;
     186    class ThreadPool;
     187    template <class T>
     188    class WeakPtr;
    165189    class WindowEventListener;
    166190    class XMLFile;
     
    173197    class XMLPortParamContainer;
    174198
    175     // game states
    176     class Game;
    177     class GameState;
    178     struct GameStateInfo;
    179     struct GameStateTreeNode;
    180 
    181     // input
     199    // Input
    182200    class BaseCommand;
    183201    class BufferedParamCommand;
    184202    class Button;
    185     class CalibratorCallback;
    186203    class HalfAxis;
    187204    class InputBuffer;
     
    192209    class InputManager;
    193210    class InputState;
     211    struct InputStatePriority;
     212    class JoyStickQuantityListener;
    194213    class JoyStick;
     214    class KeyBinder;
     215    class KeyBinderManager;
     216    class Keyboard;
     217    class KeyDetector;
     218    class KeyEvent;
    195219    class Mouse;
    196     class Keyboard;
    197     class KeyBinder;
    198     class KeyDetector;
    199220    class ParamCommand;
    200221    class SimpleCommand;
    201 
    202 
    203     // multithreading
    204     class Thread;
    205     class ThreadPool;
    206222}
    207223
     
    282298namespace orxonox
    283299{
    284     using ticpp::Document;
    285300    using ticpp::Element;
    286     using ticpp::Declaration;
    287     using ticpp::StylesheetReference;
    288     using ticpp::Text;
    289     using ticpp::Comment;
    290     using ticpp::Attribute;
    291 }
    292 
     301}
    293302
    294303#endif /* _CorePrereqs_H__ */
  • code/trunk/src/libraries/core/Event.cc

    r5781 r5929  
    3030
    3131#include "BaseObject.h"
    32 #include "Executor.h"
     32#include "Identifier.h"
    3333
    3434namespace orxonox
    3535{
    36     EventContainer::~EventContainer()
     36    /**
     37        @brief Destructor: Deletes the functor of the event state.
     38    */
     39    EventState::~EventState()
    3740    {
    38         delete this->eventfunction_;
     41        if (this->statefunction_)
     42            delete this->statefunction_;
    3943    }
    4044
    41     void EventContainer::process(BaseObject* object, const Event& event)
     45    /**
     46        @brief Processes an event (calls the set-function if the necessary conditions are met).
     47       
     48        @param event     The fired event
     49        @param object    The object whose state is affected by the event (only needed for debug output)
     50    */
     51    void EventState::process(const Event& event, BaseObject* object)
    4252    {
    43         if (this->bActive_)
     53        if (this->bProcessingEvent_)
    4454        {
    45             COUT(2) << "Warning: Detected Event loop in section \"" << this->eventname_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
     55            COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
    4656            return;
    4757        }
    4858
    49         this->bActive_ = true;
     59        this->bProcessingEvent_ = true;
    5060
    51         if (this->eventname_ == event.sectionname_)
     61        // check if the originator is an instance of the requested class
     62        if (event.originator_->isA(this->subclass_))
    5263        {
    53             if (event.originator_->isA(this->subclass_))
     64            // actualize the activationcounter
     65            if (event.activate_)
     66                ++this->activeEvents_;
     67            else
    5468            {
    55                 if (event.activate_)
    56                     ++this->activeEvents_;
    57                 else
     69                --this->activeEvents_;
     70
     71                if (this->activeEvents_ < 0)
     72                    this->activeEvents_ = 0;
     73            }
     74
     75            if (this->statefunction_->getParamCount() == 0 && event.activate_)
     76            {
     77                // if the eventfunction doesn't have a state, just call it whenever an activation-event comes in
     78                (*this->statefunction_)();
     79            }
     80            else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
     81            {
     82                // if the eventfunction needs a state, we just call the function if the state changed from 0 to 1 (state = true) or from 1 to 0 (state = false) [but not if activeEvents_ is > 1]
     83                if (this->statefunction_->getParamCount() == 1)
    5884                {
    59                     --this->activeEvents_;
    60 
    61                     if (this->activeEvents_ < 0)
    62                         this->activeEvents_ = 0;
     85                    // one argument: just the eventstate
     86                    (*this->statefunction_)(this->activeEvents_);
    6387                }
    64 
    65                 if (this->eventfunction_->getParamCount() == 0 && event.activate_)
    66                     (*this->eventfunction_)();
    67                 else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
     88                else if (this->statefunction_->getParamCount() >= 2)
    6889                {
    69                     if (this->eventfunction_->getParamCount() == 1)
    70                         (*this->eventfunction_)(this->activeEvents_);
    71                     else if (this->eventfunction_->getParamCount() >= 2 && event.castedOriginator_)
    72                         (*this->eventfunction_)(this->activeEvents_, event.castedOriginator_);
     90                    // two arguments: the eventstate and the originator
     91                    if (this->subclass_->isExactlyA(ClassIdentifier<BaseObject>::getIdentifier()))
     92                    {
     93                        // if the subclass is BaseObject, we don't have to cast the pointer
     94                        (*this->statefunction_)(this->activeEvents_, event.originator_);
     95                    }
     96                    else
     97                    {
     98                        // else cast the pointer to the desired class
     99                        void* castedOriginator = event.originator_->getDerivedPointer(this->subclass_->getClassID());
     100                        (*this->statefunction_)(this->activeEvents_, castedOriginator);
     101                    }
    73102                }
    74103            }
    75104        }
    76105
    77         this->bActive_ = false;
     106        this->bProcessingEvent_ = false;
    78107    }
    79108}
  • code/trunk/src/libraries/core/Event.h

    r5781 r5929  
    3535namespace orxonox
    3636{
     37    /**
     38        @brief The Event struct contains information about a fired Event.
     39    */
    3740    struct _CoreExport Event
    3841    {
    39             Event(bool activate, BaseObject* originator) : activate_(activate), originator_(originator), castedOriginator_(0) {}
     42        Event(bool activate, BaseObject* originator, const std::string& name) : activate_(activate), originator_(originator), name_(name) {}
    4043
    41             bool        activate_;
    42             BaseObject* originator_;
    43             void*       castedOriginator_;
    44             std::string sectionname_;
     44        bool        activate_;   //!< True if this is an activating event (the event source was inactive before and just triggered the event) - false otherwise
     45        std::string statename_;  //!< The name of the state this event affects
     46        BaseObject* originator_; //!< The object which triggered this event
     47        std::string name_;       //!< The name of this event
    4548    };
    4649
    47     class _CoreExport EventContainer
     50    /**
     51        @brief The EventState contains information about an event state.
     52       
     53        An event state is a state of an object, which can be changed by events.
     54        Event states are changed through functions. Possible functions headers for set event states are:
     55         - memoryless state: function()
     56         - boolean state:    function(bool state)
     57         - individual state: function(bool state, SomeClass originator)
     58         
     59        Note that SomeClass may be any class deriving from BaseObject. You will not receive events from originators of other classes.
     60        The actual class for SomeClass must be specified as the second argument of the XMLPortEventState macro.
     61       
     62        The this pointer of the affected object is hidden in the functors, because the events are processed in the BaseObject, but some
     63        statefunctions may be from child-classes.
     64    */
     65    class _CoreExport EventState
    4866    {
    4967        public:
    50             EventContainer(const std::string& eventname, Executor* eventfunction, Identifier* subclass) : bActive_(false), eventname_(eventname), eventfunction_(eventfunction), subclass_(subclass), activeEvents_(0) {}
    51             virtual ~EventContainer();
     68            EventState(Functor* statefunction, Identifier* subclass) : bProcessingEvent_(false), activeEvents_(0), statefunction_(statefunction), subclass_(subclass) {}
     69            virtual ~EventState();
    5270
    53             void process(BaseObject* object, const Event& event);
     71            void process(const Event& event, BaseObject* object);
     72           
     73            Functor* getFunctor() const
     74                { return this->statefunction_; }
    5475
    5576        private:
    56             bool bActive_;
    57             std::string eventname_;
    58             Executor* eventfunction_;
    59             Identifier* subclass_;
    60 
    61             int activeEvents_;
     77            bool        bProcessingEvent_;  //!< This becomes true while the container processes an event (used to prevent loops)
     78            int         activeEvents_;      //!< The number of events which affect this state and are currently active
     79            Functor*    statefunction_;     //!< A functor to set the state
     80            Identifier* subclass_;          //!< Originators must be an instance of this class (usually BaseObject, but some statefunctions allow a second argument with an originator of a specific class)
    6281    };
    6382}
  • code/trunk/src/libraries/core/EventIncludes.h

    r5781 r5929  
    3232#include "CorePrereqs.h"
    3333#include "Executor.h"
     34#include "XMLPort.h"
    3435
    35 #define ORXONOX_SET_EVENT(classname, eventname, functionname, event) \
    36     ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject)
     36/**
     37    @brief Defines a new event state (a state of the object which can be changed by events).
     38   
     39    @param classname    The name of this class
     40    @param subclassname Usually BaseObject - if different, only instances of this class can send events to this object
     41    @param statename    The name (string) of this state
     42    @param function     The function which should be used to set the state
     43    @param xmlelement   Argument for XMLPort
     44    @param mode         Argument for XMLPort
     45*/
     46#define XMLPortEventState(classname, subclassname, statename, function, xmlelement, mode) \
     47    orxonox::EventState* containername##function = this->getEventState(statename); \
     48    if (!containername##function) \
     49    { \
     50        containername##function = new orxonox::EventState(orxonox::createFunctor(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
     51        this->addEventState(statename, containername##function); \
     52    } \
     53    XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
    3754
    38 #define ORXONOX_SET_EVENT_TEMPLATE(classname, eventname, functionname, event, ...) \
    39     ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject, __VA_ARGS__)
     55/**
     56    @brief Like XMLPortEventState but with additional template arguments to identify the function of the state (if ambiguous).
     57*/
     58#define XMLPortEventStateTemplate(classname, subclassname, statename, function, xmlelement, mode, ...) \
     59    orxonox::EventState* containername##function = this->getEventState(statename); \
     60    if (!containername##function) \
     61    { \
     62        containername##function = new orxonox::EventState(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
     63        this->addEventState(statename, containername##function); \
     64    } \
     65    XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
    4066
    41 #define ORXONOX_SET_SUBCLASS_EVENT(classname, eventname, functionname, event, subclassname) \
    42     ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname)
     67#define XMLPortEventStateIntern(name, classname, statename, xmlelement, mode) \
     68    static orxonox::ExecutorMember<classname>* xmlsetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
     69    static orxonox::ExecutorMember<classname>* xmlgetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
     70    XMLPortObjectGeneric(xmlport##name, classname, orxonox::BaseObject, statename, xmlsetfunctor##name, xmlgetfunctor##name, xmlelement, mode, false, true)
     71   
    4372
    44 #define ORXONOX_SET_SUBCLASS_EVENT_TEMPLATE(classname, eventname, functionname, event, subclassname, ...) \
    45     ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname, __VA_ARGS__)
     73/**
     74    @brief Defines a new event name for a class. Named events can only have names which were defined with this macro.
     75   
     76    @param classname The name of the class
     77    @param name      The name of the event
     78*/
     79#define CreateEventName(classname, name) \
     80    static std::string eventname##classname##name = #name
    4681
    47 #define ORXONOX_SET_EVENT_GENERIC(containername, classname, eventname, functionname, event, subclassname) \
    48     orxonox::EventContainer* containername = this->getEventContainer(eventname); \
    49     if (!containername) \
    50     { \
    51         ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
    52         executor->setObject(this); \
    53         containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
    54         this->addEventContainer(eventname, containername); \
    55     } \
    56     event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
    57     containername->process(this, event)
    58 
    59 #define ORXONOX_SET_EVENT_GENERIC_TEMPLATE(containername, classname, eventname, functionname, event, subclassname, ...) \
    60     orxonox::EventContainer* containername = this->getEventContainer(eventname); \
    61     if (!containername) \
    62     { \
    63         ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
    64         executor->setObject(this); \
    65         containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
    66         this->addEventContainer(eventname, containername); \
    67     } \
    68     event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
    69     containername->process(this, event)
    70 
     82/**
     83    @brief This macro is needed to fire an event with this name. The event name must previously be declared with @ref CreateEventName.
     84*/   
     85#define FireEventName(classname, name) \
     86    eventname##classname##name
     87 
    7188#endif /* _EventIncludes_H__ */
  • code/trunk/src/libraries/core/Functor.h

    r5738 r5929  
    191191
    192192
    193 #define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams
    194 #define FUNCTOR_TEMPLATE000
    195 #define FUNCTOR_TEMPLATE001 template <class P1>
    196 #define FUNCTOR_TEMPLATE002 template <class P1, class P2>
    197 #define FUNCTOR_TEMPLATE003 template <class P1, class P2, class P3>
    198 #define FUNCTOR_TEMPLATE004 template <class P1, class P2, class P3, class P4>
    199 #define FUNCTOR_TEMPLATE005 template <class P1, class P2, class P3, class P4, class P5>
    200 #define FUNCTOR_TEMPLATE010 template <class R>
    201 #define FUNCTOR_TEMPLATE011 template <class R, class P1>
    202 #define FUNCTOR_TEMPLATE012 template <class R, class P1, class P2>
    203 #define FUNCTOR_TEMPLATE013 template <class R, class P1, class P2, class P3>
    204 #define FUNCTOR_TEMPLATE014 template <class R, class P1, class P2, class P3, class P4>
    205 #define FUNCTOR_TEMPLATE015 template <class R, class P1, class P2, class P3, class P4, class P5>
    206 #define FUNCTOR_TEMPLATE100 template <class T>
    207 #define FUNCTOR_TEMPLATE101 template <class T, class P1>
    208 #define FUNCTOR_TEMPLATE102 template <class T, class P1, class P2>
    209 #define FUNCTOR_TEMPLATE103 template <class T, class P1, class P2, class P3>
    210 #define FUNCTOR_TEMPLATE104 template <class T, class P1, class P2, class P3, class P4>
    211 #define FUNCTOR_TEMPLATE105 template <class T, class P1, class P2, class P3, class P4, class P5>
    212 #define FUNCTOR_TEMPLATE110 template <class T, class R>
    213 #define FUNCTOR_TEMPLATE111 template <class T, class R, class P1>
    214 #define FUNCTOR_TEMPLATE112 template <class T, class R, class P1, class P2>
    215 #define FUNCTOR_TEMPLATE113 template <class T, class R, class P1, class P2, class P3>
    216 #define FUNCTOR_TEMPLATE114 template <class T, class R, class P1, class P2, class P3, class P4>
    217 #define FUNCTOR_TEMPLATE115 template <class T, class R, class P1, class P2, class P3, class P4, class P5>
     193#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams, additionalobject) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams(additionalobject)
     194#define FUNCTOR_TEMPLATE000(additionalobject)
     195#define FUNCTOR_TEMPLATE001(additionalobject) template <class P1>
     196#define FUNCTOR_TEMPLATE002(additionalobject) template <class P1, class P2>
     197#define FUNCTOR_TEMPLATE003(additionalobject) template <class P1, class P2, class P3>
     198#define FUNCTOR_TEMPLATE004(additionalobject) template <class P1, class P2, class P3, class P4>
     199#define FUNCTOR_TEMPLATE005(additionalobject) template <class P1, class P2, class P3, class P4, class P5>
     200#define FUNCTOR_TEMPLATE010(additionalobject) template <class R>
     201#define FUNCTOR_TEMPLATE011(additionalobject) template <class R, class P1>
     202#define FUNCTOR_TEMPLATE012(additionalobject) template <class R, class P1, class P2>
     203#define FUNCTOR_TEMPLATE013(additionalobject) template <class R, class P1, class P2, class P3>
     204#define FUNCTOR_TEMPLATE014(additionalobject) template <class R, class P1, class P2, class P3, class P4>
     205#define FUNCTOR_TEMPLATE015(additionalobject) template <class R, class P1, class P2, class P3, class P4, class P5>
     206#define FUNCTOR_TEMPLATE100(additionalobject) template <class T FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     207#define FUNCTOR_TEMPLATE101(additionalobject) template <class T, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     208#define FUNCTOR_TEMPLATE102(additionalobject) template <class T, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     209#define FUNCTOR_TEMPLATE103(additionalobject) template <class T, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     210#define FUNCTOR_TEMPLATE104(additionalobject) template <class T, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     211#define FUNCTOR_TEMPLATE105(additionalobject) template <class T, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     212#define FUNCTOR_TEMPLATE110(additionalobject) template <class T, class R FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     213#define FUNCTOR_TEMPLATE111(additionalobject) template <class T, class R, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     214#define FUNCTOR_TEMPLATE112(additionalobject) template <class T, class R, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     215#define FUNCTOR_TEMPLATE113(additionalobject) template <class T, class R, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     216#define FUNCTOR_TEMPLATE114(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     217#define FUNCTOR_TEMPLATE115(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
     218
     219
     220
     221#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT##additionalobject
     222#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT0
     223#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT1 , class O
    218224
    219225
     
    317323
    318324#define CREATE_STATIC_FUNCTOR(returnvalue, numparams) \
    319     FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
     325    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
    320326    class FunctorStatic##returnvalue##numparams : public FunctorStatic \
    321327    { \
     
    347353    \
    348354    \
    349     FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
     355    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
    350356    inline FunctorStatic##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(0, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
    351357    { \
     
    358364
    359365#define CREATE_MEMBER_FUNCTOR(returnvalue, numparams) \
    360     FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
     366    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
    361367    class FunctorMember##returnvalue##numparams : public FunctorMember<T> \
    362368    { \
     
    391397    \
    392398    \
    393     FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
     399    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
    394400    class FunctorConstMember##returnvalue##numparams : public FunctorMember<T> \
    395401    { \
     
    423429    \
    424430    \
    425     FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
     431    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
    426432    inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
    427433    { \
     
    430436    \
    431437    \
    432     FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
     438    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
    433439    inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const) \
    434440    { \
    435441        return new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
     442    } \
     443    \
     444    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
     445    inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)), O* object) \
     446    { \
     447        FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
     448        functor->setObject(object); \
     449        return functor; \
     450    } \
     451    \
     452    \
     453    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
     454    inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const, O* object) \
     455    { \
     456        FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
     457        functor->setObject(object); \
     458        return functor; \
    436459    }
    437460
  • code/trunk/src/libraries/core/GUIManager.cc

    r5781 r5929  
    4949#endif
    5050
     51#include "util/Clock.h"
    5152#include "util/Debug.h"
    5253#include "util/Exception.h"
    5354#include "util/OrxAssert.h"
    5455#include "Core.h"
    55 #include "Clock.h"
    5656#include "LuaState.h"
     57#include "PathConfig.h"
    5758#include "Resource.h"
    5859
     
    6263    {
    6364    public:
    64             void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
     65        void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
    6566        {
    6667            int orxonoxLevel = CEGUI::Standard;
     
    100101        : renderWindow_(renderWindow)
    101102        , resourceProvider_(0)
     103        , camera_(NULL)
    102104    {
    103105        using namespace CEGUI;
     
    116118        // Create our own logger to specify the filepath
    117119        std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
    118         ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
     120        ceguiLogger->setLogFilename(PathConfig::getLogPathString() + "cegui.log");
    119121        // set the log level according to ours (translate by subtracting 1)
    120122        ceguiLogger->setLoggingLevel(
     
    173175    void GUIManager::setCamera(Ogre::Camera* camera)
    174176    {
     177        this->camera_ = camera;
    175178        if (camera == NULL)
    176179            this->guiRenderer_->setTargetSceneManager(0);
  • code/trunk/src/libraries/core/GUIManager.h

    r5781 r5929  
    7171
    7272        void setCamera(Ogre::Camera* camera);
     73        Ogre::Camera* getCamera() { return this->camera_; }
    7374
    7475        static GUIManager* getInstancePtr() { return singletonPtr_s; }
     
    101102        CEGUI::Logger*                       ceguiLogger_;      //!< CEGUI's logger to be able to log CEGUI errors in our log
    102103        std::map<std::string, PlayerInfo*>   players_;          //!< Stores the player (owner) for each gui
     104        Ogre::Camera*                        camera_;           //!< Camera used to render the scene with the GUI
    103105
    104106        static GUIManager*                   singletonPtr_s;    //!< Singleton reference to GUIManager
  • code/trunk/src/libraries/core/Game.cc

    r5781 r5929  
    3838#include <boost/weak_ptr.hpp>
    3939
     40#include "util/Clock.h"
    4041#include "util/Debug.h"
    4142#include "util/Exception.h"
     
    4344#include "util/Sleep.h"
    4445#include "util/SubString.h"
    45 #include "Clock.h"
    4646#include "CommandLine.h"
    4747#include "ConsoleCommand.h"
     
    5757        { Game::getInstance().stop(); }
    5858    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
     59    static void printFPS()
     60        { COUT(0) << Game::getInstance().getAvgFPS() << std::endl; }
     61    SetConsoleCommandShortcutExternAlias(printFPS, "printFPS");
     62    static void printTickTime()
     63        { COUT(0) << Game::getInstance().getAvgTickTime() << std::endl; }
     64    SetConsoleCommandShortcutExternAlias(printTickTime, "printTickTime");
    5965
    6066    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
     
    111117    Game::Game(const std::string& cmdLine)
    112118        // Destroy factories before the Core!
    113         : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
     119        : gsFactoryDestroyer_(Game::GameStateFactory::getFactories(), &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
    114120    {
    115121        this->bAbort_ = false;
     
    410416                requestedNodes.push_back(currentNode);
    411417            }
     418            if (currentNode == NULL)
     419                requestedNodes.clear();
    412420        }
    413421
     
    457465    {
    458466        // Split string into pieces of the form whitespacesText
    459         std::vector<std::pair<std::string, unsigned> > stateStrings;
     467        std::vector<std::pair<std::string, int> > stateStrings;
    460468        size_t pos = 0;
    461469        size_t startPos = 0;
    462470        while (pos < str.size())
    463471        {
    464             unsigned indentation = 0;
     472            int indentation = 0;
    465473            while(pos < str.size() && str[pos] == ' ')
    466474                ++indentation, ++pos;
     
    470478            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
    471479        }
    472         unsigned int currentLevel = 0;
    473         shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
    474         for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
    475         {
    476             std::string newStateName = it->first;
    477             unsigned newLevel = it->second + 1; // empty root is 0
    478             if (!this->checkState(newStateName))
    479                 ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
    480             if (newStateName == this->rootStateNode_->name_)
     480        if (stateStrings.empty())
     481            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
     482        // Add element with large identation to detect the last with just an iterator
     483        stateStrings.push_back(std::make_pair("", -1));
     484
     485        // Parse elements recursively
     486        std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
     487        parseStates(begin, this->rootStateNode_);
     488    }
     489
     490    /*** Internal ***/
     491
     492    void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
     493    {
     494        SubString tokens(it->first, ",");
     495        std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
     496
     497        for (unsigned int i = 0; i < tokens.size(); ++i)
     498        {
     499            it = startIt; // Reset iterator to the beginning of the sub tree
     500            if (!this->checkState(tokens[i]))
     501                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
     502            if (tokens[i] == this->rootStateNode_->name_)
    481503                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
    482             shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
    483             newNode->name_ = newStateName;
    484 
    485             if (newLevel <= currentLevel)
    486             {
    487                 do
    488                     currentNode = currentNode->parent_.lock();
    489                 while (newLevel <= --currentLevel);
    490             }
    491             if (newLevel == currentLevel + 1)
    492             {
    493                 // Add the child
    494                 newNode->parent_ = currentNode;
    495                 currentNode->children_.push_back(newNode);
    496             }
    497             else
    498                 ThrowException(GameState, "Indentation error while parsing the hierarchy.");
    499             currentNode = newNode;
    500             currentLevel = newLevel;
    501         }
    502     }
    503 
    504     /*** Internal ***/
     504            shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
     505            node->name_ = tokens[i];
     506            node->parent_ = currentNode;
     507            currentNode->children_.push_back(node);
     508
     509            int currentLevel = it->second;
     510            ++it;
     511            while (it->second != -1)
     512            {
     513                if (it->second <= currentLevel)
     514                    break;
     515                else if (it->second == currentLevel + 1)
     516                    parseStates(it, node);
     517                else
     518                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
     519            }
     520        }
     521    }
    505522
    506523    void Game::loadGraphics()
    507524    {
    508         if (!GameMode::bShowsGraphics_s)
     525        if (!GameMode::showsGraphics())
    509526        {
    510527            core_->loadGraphics();
    511528            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
    512             GameMode::bShowsGraphics_s = true;
    513529
    514530            // Construct all the GameStates that require graphics
     
    531547    void Game::unloadGraphics()
    532548    {
    533         if (GameMode::bShowsGraphics_s)
     549        if (GameMode::showsGraphics())
    534550        {
    535551            // Destroy all the GameStates that require graphics
     
    543559
    544560            core_->unloadGraphics();
    545             GameMode::bShowsGraphics_s = false;
    546561        }
    547562    }
     
    607622    }
    608623
    609     std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
     624    /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories()
     625    {
     626        static std::map<std::string, shared_ptr<GameStateFactory> > factories;
     627        return factories;
     628    }
    610629
    611630    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
    612631    {
    613         std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = factories_s.find(info.className);
    614         assert(it != factories_s.end());
     632        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
     633        assert(it != getFactories().end());
    615634        return it->second->fabricateInternal(info);
    616635    }
  • code/trunk/src/libraries/core/Game.h

    r5747 r5929  
    117117            template <class T>
    118118            static void createFactory(const std::string& className)
    119                 { factories_s[className].reset(new TemplateGameStateFactory<T>()); }
     119                { getFactories()[className].reset(new TemplateGameStateFactory<T>()); }
    120120
    121121            virtual shared_ptr<GameState> fabricateInternal(const GameStateInfo& info) = 0;
    122             static std::map<std::string, shared_ptr<GameStateFactory> > factories_s;
     122            static std::map<std::string, shared_ptr<GameStateFactory> >& getFactories();
    123123        };
    124124        template <class T>
     
    143143        void unloadGraphics();
    144144
     145        void parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode);
    145146        bool checkState(const std::string& name) const;
    146147        void loadState(const std::string& name);
  • code/trunk/src/libraries/core/GameMode.cc

    r5781 r5929  
    2727 */
    2828
    29 /**
    30     @file
    31     @brief Implementation of the GameMode class.
    32 */
    33 
    3429#include "GameMode.h"
    3530
     
    3732{
    3833    bool GameMode::bShowsGraphics_s = false;
     34    bool GameMode::bPlaysSound_s    = false;
    3935    bool GameMode::bHasServer_s     = false;
    4036    bool GameMode::bIsClient_s      = false;
  • code/trunk/src/libraries/core/GameMode.h

    r5781 r5929  
    4141    class _CoreExport GameMode
    4242    {
    43         friend class Game;
     43        friend class Core;
    4444
    4545        public:
    4646            static bool showsGraphics() { return bShowsGraphics_s; }
     47            static bool playsSound()    { return bPlaysSound_s; }
    4748            static bool hasServer()     { return bHasServer_s; }
    4849            static bool isClient()      { return bIsClient_s; }
     
    5051            static bool isMaster()      { return bIsMaster_s; }
    5152
     53            static void setPlaysSound   (bool val) { bPlaysSound_s    = val; }
    5254            static void setHasServer    (bool val) { bHasServer_s     = val; updateIsMaster(); }
    5355            static void setIsClient     (bool val) { bIsClient_s      = val; updateIsMaster(); }
     
    6567
    6668            static bool bShowsGraphics_s;                   //!< global variable that tells whether to show graphics
     69            static bool bPlaysSound_s;                      //!< global variable that tells whether to sound works
    6770            static bool bHasServer_s;                       //!< global variable that tells whether this is a server
    6871            static bool bIsClient_s;
  • code/trunk/src/libraries/core/GameState.h

    r5738 r5929  
    4040#include <map>
    4141#include <string>
     42#include "util/UtilPrereqs.h"
    4243
    4344namespace orxonox
  • code/trunk/src/libraries/core/GraphicsManager.cc

    r5781 r5929  
    4848
    4949#include "SpecialConfig.h"
     50#include "util/Clock.h"
    5051#include "util/Exception.h"
    5152#include "util/StringUtils.h"
    5253#include "util/SubString.h"
    53 #include "Clock.h"
    5454#include "ConsoleCommand.h"
    5555#include "ConfigValueIncludes.h"
    5656#include "CoreIncludes.h"
    57 #include "Core.h"
    5857#include "Game.h"
    5958#include "GameMode.h"
    6059#include "Loader.h"
    6160#include "MemoryArchive.h"
     61#include "PathConfig.h"
    6262#include "WindowEventListener.h"
    6363#include "XMLFile.h"
     
    102102
    103103        // At first, add the root paths of the data directories as resource locations
    104         Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
     104        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem", "dataRoot", false);
    105105        // Load resources
    106106        resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
     
    109109
    110110        // Only for development runs
    111         if (Core::isDevelopmentRun())
    112         {
    113             Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
     111        if (PathConfig::isDevelopmentRun())
     112        {
     113            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
    114114            extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
    115115            extResources_->setLuaSupport(false);
     
    130130    GraphicsManager::~GraphicsManager()
    131131    {
     132        Loader::unload(debugOverlay_.get());
     133
    132134        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
    133135        // TODO: Destroy the console command
     136
     137        // Undeclare the resources
     138        Loader::unload(resources_.get());
     139        if (PathConfig::isDevelopmentRun())
     140            Loader::unload(extResources_.get());
    134141    }
    135142
     
    241248        }
    242249
    243         boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
    244         boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
     250        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
     251        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
    245252
    246253        // create a new logManager
     
    313320
    314321        // add console commands
    315         FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
    316         ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
     322        ccPrintScreen_ = createConsoleCommand(createFunctor(&GraphicsManager::printScreen, this), "printScreen");
    317323        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
    318324    }
    319325
     326    void GraphicsManager::loadDebugOverlay()
     327    {
     328        // Load debug overlay to show info about fps and tick time
     329        COUT(4) << "Loading Debug Overlay..." << std::endl;
     330        debugOverlay_.reset(new XMLFile("debug.oxo"));
     331        Loader::open(debugOverlay_.get());
     332    }
     333
     334    /**
     335    @note
     336        A note about the Ogre::FrameListener: Even though we don't use them,
     337        they still get called. However, the delta times are not correct (except
     338        for timeSinceLastFrame, which is the most important). A little research
     339        as shown that there is probably only one FrameListener that doesn't even
     340        need the time. So we shouldn't run into problems.
     341    */
    320342    void GraphicsManager::update(const Clock& time)
    321343    {
     
    418440        assert(this->renderWindow_);
    419441       
    420         this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
     442        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".jpg");
    421443    }
    422444}
  • code/trunk/src/libraries/core/GraphicsManager.h

    r5781 r5929  
    7171
    7272        void upgradeToGraphics();
     73        void loadDebugOverlay();
    7374        bool rendererLoaded() const { return renderWindow_ != NULL; }
    7475
     
    99100        Ogre::Viewport*     viewport_;                 //!< default full size viewport
    100101
    101         // XML files for the resources
     102        // XML files for the resources and the debug overlay
    102103        shared_ptr<XMLFile> resources_;                //!< XML with resource locations
    103104        shared_ptr<XMLFile> extResources_;             //!< XML with resource locations in the external path (only for dev runs)
     105        shared_ptr<XMLFile> debugOverlay_;             //!< XML with various debug overlays
    104106
    105107        // config values
  • code/trunk/src/libraries/core/Identifier.cc

    r5781 r5929  
    3939#include "ConfigValueContainer.h"
    4040#include "ConsoleCommand.h"
    41 #include "Factory.h"
     41#include "ClassFactory.h"
    4242#include "XMLPort.h"
    4343
     
    6161        this->bSetName_ = false;
    6262        this->factory_ = 0;
    63         this->bLoadable_ = true;
     63        this->bLoadable_ = false;
    6464
    6565        this->bHasConfigValues_ = false;
    6666        this->bHasConsoleCommands_ = false;
    6767
    68         this->children_ = new std::set<const Identifier*>();
    69         this->directChildren_ = new std::set<const Identifier*>();
    70 
    7168        // Default network ID is the class ID
    7269        this->networkID_ = this->classID_;
     
    7875    Identifier::~Identifier()
    7976    {
    80         delete this->children_;
    81         delete this->directChildren_;
    8277        delete this->objects_;
    8378
     
    118113            // There is already an entry: return it and delete the proposal
    119114            delete proposal;
    120             return (*it).second;
     115            return it->second;
    121116        }
    122117        else
     
    165160            {
    166161                // Tell the parent we're one of it's children
    167                 (*it)->getChildrenIntern().insert((*it)->getChildrenIntern().end(), this);
     162                (*it)->children_.insert((*it)->children_.end(), this);
    168163
    169164                // Erase all parents of our parent from our direct-parent-list
     
    187182            {
    188183                // Tell the parent we're one of it's direct children
    189                 (*it)->getDirectChildrenIntern().insert((*it)->getDirectChildrenIntern().end(), this);
     184                (*it)->directChildren_.insert((*it)->directChildren_.end(), this);
    190185
    191186                // Create the super-function dependencies
     
    196191
    197192    /**
     193        @brief Creates the class-hierarchy by creating and destroying one object of each type.
     194    */
     195    void Identifier::createClassHierarchy()
     196    {
     197        COUT(3) << "*** Identifier: Create class-hierarchy" << std::endl;
     198        Identifier::startCreatingHierarchy();
     199        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMap().begin(); it != Identifier::getStringIdentifierMap().end(); ++it)
     200        {
     201            // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
     202            if (it->second->hasFactory())
     203            {
     204                BaseObject* temp = it->second->fabricate(0);
     205                temp->destroy();
     206            }
     207        }
     208        Identifier::stopCreatingHierarchy();
     209        COUT(3) << "*** Identifier: Finished class-hierarchy creation" << std::endl;
     210    }
     211
     212    /**
    198213        @brief Destroys all Identifiers. Called when exiting the program.
    199214    */
     
    214229            this->name_ = name;
    215230            this->bSetName_ = true;
    216             Identifier::getIdentifierMapIntern()[name] = this;
    217             Identifier::getLowercaseIdentifierMapIntern()[getLowercase(name)] = this;
     231            Identifier::getStringIdentifierMapIntern()[name] = this;
     232            Identifier::getLowercaseStringIdentifierMapIntern()[getLowercase(name)] = this;
     233            Identifier::getIDIdentifierMapIntern()[this->networkID_] = this;
    218234        }
    219235    }
     
    235251            COUT(1) << "Aborting..." << std::endl;
    236252            abort();
    237             return NULL;
    238         }
    239     }
    240 
    241     /**
    242         @brief Sets the network ID to a new value and changes the entry in the Factory.
     253            return 0;
     254        }
     255    }
     256
     257    /**
     258        @brief Sets the network ID to a new value and changes the entry in the ID-Identifier-map.
    243259        @param id The new network ID
    244260    */
    245261    void Identifier::setNetworkID(uint32_t id)
    246262    {
    247         Factory::changeNetworkID(this, this->networkID_, id);
     263//        Identifier::getIDIdentifierMapIntern().erase(this->networkID_);
     264        Identifier::getIDIdentifierMapIntern()[id] = this;
    248265        this->networkID_ = id;
    249266    }
     
    291308    bool Identifier::isParentOf(const Identifier* identifier) const
    292309    {
    293         return (this->children_->find(identifier) != this->children_->end());
     310        return (this->children_.find(identifier) != this->children_.end());
    294311    }
    295312
     
    300317    bool Identifier::isDirectParentOf(const Identifier* identifier) const
    301318    {
    302         return (this->directChildren_->find(identifier) != this->directChildren_->end());
    303     }
    304 
    305     /**
    306         @brief Returns the map that stores all Identifiers.
     319        return (this->directChildren_.find(identifier) != this->directChildren_.end());
     320    }
     321
     322    /**
     323        @brief Returns the map that stores all Identifiers with their names.
    307324        @return The map
    308325    */
    309     std::map<std::string, Identifier*>& Identifier::getIdentifierMapIntern()
     326    std::map<std::string, Identifier*>& Identifier::getStringIdentifierMapIntern()
    310327    {
    311328        static std::map<std::string, Identifier*> identifierMap;
     
    314331
    315332    /**
    316         @brief Returns the map that stores all Identifiers.
     333        @brief Returns the map that stores all Identifiers with their names in lowercase.
    317334        @return The map
    318335    */
    319     std::map<std::string, Identifier*>& Identifier::getLowercaseIdentifierMapIntern()
     336    std::map<std::string, Identifier*>& Identifier::getLowercaseStringIdentifierMapIntern()
    320337    {
    321338        static std::map<std::string, Identifier*> lowercaseIdentifierMap;
    322339        return lowercaseIdentifierMap;
     340    }
     341
     342    /**
     343        @brief Returns the map that stores all Identifiers with their network IDs.
     344        @return The map
     345    */
     346    std::map<uint32_t, Identifier*>& Identifier::getIDIdentifierMapIntern()
     347    {
     348        static std::map<uint32_t, Identifier*> identifierMap;
     349        return identifierMap;
     350    }
     351
     352    /**
     353        @brief Returns the Identifier with a given name.
     354        @param name The name of the wanted Identifier
     355        @return The Identifier
     356    */
     357    Identifier* Identifier::getIdentifierByString(const std::string& name)
     358    {
     359        std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapIntern().find(name);
     360        if (it != Identifier::getStringIdentifierMapIntern().end())
     361            return it->second;
     362        else
     363            return 0;
     364    }
     365
     366    /**
     367        @brief Returns the Identifier with a given name in lowercase.
     368        @param name The name of the wanted Identifier
     369        @return The Identifier
     370    */
     371    Identifier* Identifier::getIdentifierByLowercaseString(const std::string& name)
     372    {
     373        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapIntern().find(name);
     374        if (it != Identifier::getLowercaseStringIdentifierMapIntern().end())
     375            return it->second;
     376        else
     377            return 0;
     378    }
     379
     380    /**
     381        @brief Returns the Identifier with a given network ID.
     382        @param id The network ID of the wanted Identifier
     383        @return The Identifier
     384    */
     385    Identifier* Identifier::getIdentifierByID(const uint32_t id)
     386    {
     387        std::map<uint32_t, Identifier*>::const_iterator it = Identifier::getIDIdentifierMapIntern().find(id);
     388        if (it != Identifier::getIDIdentifierMapIntern().end())
     389            return it->second;
     390        else
     391            return 0;
     392    }
     393
     394    /**
     395        @brief Cleans the NetworkID map (needed on clients for correct initialization)
     396    */
     397    void Identifier::clearNetworkIDs()
     398    {
     399        Identifier::getIDIdentifierMapIntern().clear();
    323400    }
    324401
     
    351428        std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_.find(varname);
    352429        if (it != configValues_.end())
    353             return ((*it).second);
     430            return it->second;
    354431        else
    355432            return 0;
     
    365442        std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_LC_.find(varname);
    366443        if (it != configValues_LC_.end())
    367             return ((*it).second);
     444            return it->second;
    368445        else
    369446            return 0;
     
    404481        std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_.find(name);
    405482        if (it != this->consoleCommands_.end())
    406             return (*it).second;
     483            return it->second;
    407484        else
    408485            return 0;
     
    418495        std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_LC_.find(name);
    419496        if (it != this->consoleCommands_LC_.end())
    420             return (*it).second;
     497            return it->second;
    421498        else
    422499            return 0;
     
    432509        std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
    433510        if (it != this->xmlportParamContainers_.end())
    434             return ((*it).second);
     511            return it->second;
    435512        else
    436513            return 0;
     
    463540        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
    464541        if (it != this->xmlportObjectContainers_.end())
    465             return ((*it).second);
     542            return it->second;
    466543        else
    467544            return 0;
     
    483560
    484561        this->xmlportObjectContainers_[sectionname] = container;
    485     }
    486 
    487     /**
    488         @brief Returns a XMLPortEventContainer that attaches an event to this class.
    489         @param sectionname The name of the section that contains the event
    490         @return The container
    491     */
    492     XMLPortObjectContainer* Identifier::getXMLPortEventContainer(const std::string& eventname)
    493     {
    494         std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
    495         if (it != this->xmlportEventContainers_.end())
    496             return ((*it).second);
    497         else
    498             return 0;
    499     }
    500 
    501     /**
    502         @brief Adds a new XMLPortEventContainer that attaches an event to this class.
    503         @param sectionname The name of the section that contains the event
    504         @param container The container
    505     */
    506     void Identifier::addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container)
    507     {
    508         std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
    509         if (it != this->xmlportEventContainers_.end())
    510         {
    511             COUT(2) << "Warning: Overwriting XMLPortEventContainer in class " << this->getName() << "." << std::endl;
    512             delete (it->second);
    513         }
    514 
    515         this->xmlportEventContainers_[eventname] = container;
    516562    }
    517563
     
    525571    {
    526572        for (std::set<const Identifier*>::const_iterator it = list.begin(); it != list.end(); ++it)
    527             out << (*it)->getName() << " ";
     573        {
     574            if (it != list.begin())
     575                out << " ";
     576            out << (*it)->getName();
     577        }
    528578
    529579        return out;
  • code/trunk/src/libraries/core/Identifier.h

    r5781 r5929  
    2929/**
    3030    @file
    31     @brief Definition of the Identifier, ClassIdentifier and SubclassIdentifier classes, implementation of the ClassIdentifier and SubclassIdentifier classes.
     31    @brief Definition of the Identifier class, definition and implementation of the ClassIdentifier class.
    3232
    3333    The Identifier contains all needed information about the class it belongs to:
     
    4545
    4646    Every Identifier is in fact a ClassIdentifier, but they are derived from Identifier.
    47 
    48     SubclassIdentifier is a separated class, acting like an Identifier, but has a given class.
    49     You can only assign Identifiers of exactly the given class or of a derivative to a SubclassIdentifier.
    5047*/
    5148
     
    9087    class _CoreExport Identifier
    9188    {
    92         template <class T>
    93         friend class SubclassIdentifier;
    94 
    95         friend class Factory;
    96 
    9789        public:
     90            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
     91            inline const std::string& getName() const { return this->name_; }
     92            void setName(const std::string& name);
     93
     94            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
     95            inline const uint32_t getNetworkID() const { return this->networkID_; }
     96            void setNetworkID(uint32_t id);
     97
     98            /** @brief Returns the unique ID of the class */
     99            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
     100
     101            /** @brief Returns the list of all existing objects of this class. @return The list */
     102            inline ObjectListBase* getObjects() const { return this->objects_; }
     103
    98104            /** @brief Sets the Factory. @param factory The factory to assign */
    99             inline void addFactory(BaseFactory* factory) { this->factory_ = factory; }
     105            inline void addFactory(Factory* factory) { this->factory_ = factory; }
     106            /** @brief Returns true if the Identifier has a Factory. */
     107            inline bool hasFactory() const { return (this->factory_ != 0); }
    100108
    101109            BaseObject* fabricate(BaseObject* creator);
     110
     111            /** @brief Returns true if the class can be loaded through XML. */
     112            inline bool isLoadable() const { return this->bLoadable_; }
     113            /** @brief Set the class to be loadable through XML or not. */
     114            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
     115
    102116            bool isA(const Identifier* identifier) const;
    103117            bool isExactlyA(const Identifier* identifier) const;
     
    107121            bool isDirectParentOf(const Identifier* identifier) const;
    108122
    109             /** @brief Returns true if the class can be loaded through XML. */
    110             inline bool isLoadable() const { return this->bLoadable_; }
    111             /** @brief Set the class to be loadable through XML or not. */
    112             inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
    113 
    114             /** @brief Returns the list of all existing objects of this class. @return The list */
    115             inline ObjectListBase* getObjects() const
    116                 { return this->objects_; }
    117 
    118             /** @brief Returns the name of the class the Identifier belongs to. @return The name */
    119             inline const std::string& getName() const { return this->name_; }
    120             void setName(const std::string& name);
    121 
    122             virtual void updateConfigValues(bool updateChildren = true) const = 0;
     123
     124            /////////////////////////////
     125            ////// Class Hierarchy //////
     126            /////////////////////////////
     127            static void createClassHierarchy();
     128
     129            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
     130            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
    123131
    124132            /** @brief Returns the parents of the class the Identifier belongs to. @return The list of all parents */
     
    130138
    131139            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
    132             inline const std::set<const Identifier*>& getChildren() const { return (*this->children_); }
     140            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
    133141            /** @brief Returns the begin-iterator of the children-list. @return The begin-iterator */
    134             inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_->begin(); }
     142            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
    135143            /** @brief Returns the end-iterator of the children-list. @return The end-iterator */
    136             inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_->end(); }
     144            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
    137145
    138146            /** @brief Returns the direct parents of the class the Identifier belongs to. @return The list of all direct parents */
     
    144152
    145153            /** @brief Returns the direct children the class the Identifier belongs to. @return The list of all direct children */
    146             inline const std::set<const Identifier*>& getDirectChildren() const { return (*this->directChildren_); }
     154            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
    147155            /** @brief Returns the begin-iterator of the direct-children-list. @return The begin-iterator */
    148             inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_->begin(); }
     156            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
    149157            /** @brief Returns the end-iterator of the direct-children-list. @return The end-iterator */
    150             inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_->end(); }
    151 
    152 
    153             /** @brief Returns the map that stores all Identifiers. @return The map */
    154             static inline const std::map<std::string, Identifier*>& getIdentifierMap() { return Identifier::getIdentifierMapIntern(); }
    155             /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers. @return The const_iterator */
    156             static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapBegin() { return Identifier::getIdentifierMap().begin(); }
    157             /** @brief Returns a const_iterator to the end of the map that stores all Identifiers. @return The const_iterator */
    158             static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapEnd() { return Identifier::getIdentifierMap().end(); }
     158            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_.end(); }
     159
     160
     161            //////////////////////////
     162            ///// Identifier Map /////
     163            //////////////////////////
     164            static void destroyAllIdentifiers();
     165
     166            static Identifier* getIdentifierByString(const std::string& name);
     167            static Identifier* getIdentifierByLowercaseString(const std::string& name);
     168            static Identifier* getIdentifierByID(uint32_t id);
     169
     170            static void clearNetworkIDs();
     171
     172            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
     173            static inline const std::map<std::string, Identifier*>& getStringIdentifierMap() { return Identifier::getStringIdentifierMapIntern(); }
     174            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names. @return The const_iterator */
     175            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapBegin() { return Identifier::getStringIdentifierMap().begin(); }
     176            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names. @return The const_iterator */
     177            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapEnd() { return Identifier::getStringIdentifierMap().end(); }
    159178
    160179            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
    161             static inline const std::map<std::string, Identifier*>& getLowercaseIdentifierMap() { return Identifier::getLowercaseIdentifierMapIntern(); }
     180            static inline const std::map<std::string, Identifier*>& getLowercaseStringIdentifierMap() { return Identifier::getLowercaseStringIdentifierMapIntern(); }
    162181            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
    163             static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapBegin() { return Identifier::getLowercaseIdentifierMap().begin(); }
     182            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapBegin() { return Identifier::getLowercaseStringIdentifierMap().begin(); }
    164183            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
    165             static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapEnd() { return Identifier::getLowercaseIdentifierMap().end(); }
    166 
     184            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapEnd() { return Identifier::getLowercaseStringIdentifierMap().end(); }
     185
     186            /** @brief Returns the map that stores all Identifiers with their IDs. @return The map */
     187            static inline const std::map<uint32_t, Identifier*>& getIDIdentifierMap() { return Identifier::getIDIdentifierMapIntern(); }
     188            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their IDs. @return The const_iterator */
     189            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapBegin() { return Identifier::getIDIdentifierMap().begin(); }
     190            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their IDs. @return The const_iterator */
     191            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapEnd() { return Identifier::getIDIdentifierMap().end(); }
     192
     193
     194            /////////////////////////
     195            ///// Config Values /////
     196            /////////////////////////
     197            virtual void updateConfigValues(bool updateChildren = true) const = 0;
     198
     199            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
     200            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
    167201
    168202            /** @brief Returns the map that stores all config values. @return The const_iterator */
     
    180214            inline std::map<std::string, ConfigValueContainer*>::const_iterator getLowercaseConfigValueMapEnd() const { return this->configValues_LC_.end(); }
    181215
     216            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
     217            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
     218            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
     219
     220
     221            ////////////////////////////
     222            ///// Console Commands /////
     223            ////////////////////////////
     224            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
     225            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
    182226
    183227            /** @brief Returns the map that stores all console commands. @return The const_iterator */
     
    195239            inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandMapEnd() const { return this->consoleCommands_LC_.end(); }
    196240
     241            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
     242            ConsoleCommand* getConsoleCommand(const std::string& name) const;
     243            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
     244
     245
     246            ///////////////////
     247            ///// XMLPort /////
     248            ///////////////////
    197249            /** @brief Returns the map that stores all XMLPort params. @return The const_iterator */
    198250            inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
     
    209261            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
    210262
    211             /** @brief Returns the map that stores all XMLPort events. @return The const_iterator */
    212             inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortEventMap() const { return this->xmlportEventContainers_; }
    213             /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort events. @return The const_iterator */
    214             inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapBegin() const { return this->xmlportEventContainers_.begin(); }
    215             /** @brief Returns a const_iterator to the end of the map that stores all XMLPort events. @return The const_iterator */
    216             inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapEnd() const { return this->xmlportEventContainers_.end(); }
    217 
    218             /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
    219             inline bool hasConfigValues() const { return this->bHasConfigValues_; }
    220             /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
    221             inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
    222 
    223             /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
    224             inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
    225 
    226             /** @brief Returns the network ID to identify a class through the network. @return the network ID */
    227             inline const uint32_t getNetworkID() const { return this->networkID_; }
    228 
    229             /** @brief Sets the network ID to a new value. @param id The new value */
    230             void setNetworkID(uint32_t id);
    231 
    232             /** @brief Returns the unique ID of the class */
    233             FORCEINLINE unsigned int getClassID() const { return this->classID_; }
    234 
    235             void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
    236             ConfigValueContainer* getConfigValueContainer(const std::string& varname);
    237             ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
    238 
    239263            void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
    240264            XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
     
    243267            XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
    244268
    245             void addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container);
    246             XMLPortObjectContainer* getXMLPortEventContainer(const std::string& eventname);
    247 
    248             ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
    249             ConsoleCommand* getConsoleCommand(const std::string& name) const;
    250             ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
    251 
    252             void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
    253 
    254             static void destroyAllIdentifiers();
    255269
    256270        protected:
     
    262276            virtual void createSuperFunctionCaller() const = 0;
    263277
    264             /** @brief Returns the map that stores all Identifiers. @return The map */
    265             static std::map<std::string, Identifier*>& getIdentifierMapIntern();
     278            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
     279
     280            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
     281            static std::map<std::string, Identifier*>& getStringIdentifierMapIntern();
    266282            /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
    267             static std::map<std::string, Identifier*>& getLowercaseIdentifierMapIntern();
     283            static std::map<std::string, Identifier*>& getLowercaseStringIdentifierMapIntern();
     284            /** @brief Returns the map that stores all Identifiers with their network IDs. @return The map */
     285            static std::map<uint32_t, Identifier*>& getIDIdentifierMapIntern();
    268286
    269287            /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
    270             inline std::set<const Identifier*>& getChildrenIntern() const { return (*this->children_); }
     288            inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
    271289            /** @brief Returns the direct children of the class the Identifier belongs to. @return The list of all direct children */
    272             inline std::set<const Identifier*>& getDirectChildrenIntern() const { return (*this->directChildren_); }
     290            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
    273291
    274292            ObjectListBase* objects_;                                      //!< The list of all objects of this class
    275293
    276294        private:
    277             /**
    278                 @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents.
    279             */
    280             inline static void startCreatingHierarchy()
    281             {
    282                 hierarchyCreatingCounter_s++;
    283                 COUT(4) << "*** Identifier: Increased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
    284             }
    285 
    286             /**
    287                 @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents.
    288             */
    289             inline static void stopCreatingHierarchy()
    290             {
    291                 hierarchyCreatingCounter_s--;
    292                 COUT(4) << "*** Identifier: Decreased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
    293             }
     295            /** @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents. */
     296            inline static void startCreatingHierarchy() { hierarchyCreatingCounter_s++; }
     297            /** @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents. */
     298            inline static void stopCreatingHierarchy()  { hierarchyCreatingCounter_s--; }
    294299
    295300            static std::map<std::string, Identifier*>& getTypeIDIdentifierMap();
     
    298303
    299304            std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
    300             std::set<const Identifier*>* children_;                        //!< The children of the class the Identifier belongs to
     305            mutable std::set<const Identifier*> children_;                 //!< The children of the class the Identifier belongs to
    301306
    302307            std::set<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to
    303             std::set<const Identifier*>* directChildren_;                  //!< The direct children of the class the Identifier belongs to
     308            mutable std::set<const Identifier*> directChildren_;           //!< The direct children of the class the Identifier belongs to
    304309
    305310            bool bCreatedOneObject_;                                       //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
     
    307312            bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
    308313            std::string name_;                                             //!< The name of the class the Identifier belongs to
    309             BaseFactory* factory_;                                         //!< The Factory, able to create new objects of the given class (if available)
     314            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
    310315            static int hierarchyCreatingCounter_s;                         //!< Bigger than zero if at least one Identifier stores its parents (its an int instead of a bool to avoid conflicts with multithreading)
    311316            uint32_t networkID_;                                           //!< The network ID to identify a class through the network
     
    323328            std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
    324329            std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
    325             std::map<std::string, XMLPortObjectContainer*> xmlportEventContainers_;    //!< All events
    326330    };
    327331
     
    348352
    349353        public:
    350             static ClassIdentifier<T> *getIdentifier();
    351             static ClassIdentifier<T> *getIdentifier(const std::string& name);
     354            static ClassIdentifier<T>* getIdentifier();
     355            static ClassIdentifier<T>* getIdentifier(const std::string& name);
    352356
    353357            bool initialiseObject(T* object, const std::string& className, bool bRootClass);
     
    380384    inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
    381385    {
    382         // check if the static field has already been filled
    383         if (ClassIdentifier<T>::classIdentifier_s == 0)
     386        // check if the Identifier already exists
     387        if (!ClassIdentifier<T>::classIdentifier_s)
    384388            ClassIdentifier<T>::initialiseIdentifier();
    385389
     
    508512#endif
    509513    }
    510 
    511 
    512     // ###############################
    513     // ###   SubclassIdentifier    ###
    514     // ###############################
    515     //! The SubclassIdentifier acts almost like an Identifier, but has some prerequisites.
    516     /**
    517         You can only assign an Identifier that belongs to a class T (or derived) to a SubclassIdentifier<T>.
    518         If you assign something else, the program aborts.
    519         Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
    520     */
    521     template <class T>
    522     class SubclassIdentifier
    523     {
    524         public:
    525             /**
    526                 @brief Constructor: Automaticaly assigns the Identifier of the given class.
    527             */
    528             SubclassIdentifier()
    529             {
    530                 this->identifier_ = ClassIdentifier<T>::getIdentifier();
    531             }
    532 
    533             /**
    534                 @brief Copyconstructor: Assigns the given Identifier.
    535                 @param identifier The Identifier
    536             */
    537             SubclassIdentifier(Identifier* identifier)
    538             {
    539                 this->operator=(identifier);
    540             }
    541 
    542             /**
    543                 @brief Overloading of the = operator: assigns the identifier and checks its type.
    544                 @param identifier The Identifier to assign
    545                 @return The SubclassIdentifier itself
    546             */
    547             SubclassIdentifier<T>& operator=(Identifier* identifier)
    548             {
    549                 if (!identifier || !identifier->isA(ClassIdentifier<T>::getIdentifier()))
    550                 {
    551                     COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
    552                     if (identifier)
    553                     {
    554                         COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
    555                         COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl;
    556                     }
    557                     else
    558                     {
    559                         COUT(1) << "Error: Can't assign NULL identifier" << std::endl;
    560                     }
    561                 }
    562                 else
    563                 {
    564                     this->identifier_ = identifier;
    565                 }
    566                 return *this;
    567             }
    568 
    569             /**
    570                 @brief Overloading of the * operator: returns the assigned identifier.
    571             */
    572             inline Identifier* operator*() const
    573             {
    574                 return this->identifier_;
    575             }
    576 
    577             /**
    578                 @brief Overloading of the -> operator: returns the assigned identifier.
    579             */
    580             inline Identifier* operator->() const
    581             {
    582                 return this->identifier_;
    583             }
    584 
    585             /**
    586                 @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
    587             */
    588             inline operator Identifier*() const
    589             {
    590                 return this->identifier_;
    591             }
    592 
    593             /**
    594                 @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
    595                 @return The new object
    596             */
    597             T* fabricate(BaseObject* creator) const
    598             {
    599                 BaseObject* newObject = this->identifier_->fabricate(creator);
    600 
    601                 // Check if the creation was successful
    602                 if (newObject)
    603                 {
    604                     return orxonox_cast<T*>(newObject);
    605                 }
    606                 else
    607                 {
    608                     // Something went terribly wrong
    609                     if (this->identifier_)
    610                     {
    611                         COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
    612                         COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
    613                         COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl;
    614                         COUT(1) << "Aborting..." << std::endl;
    615                     }
    616                     else
    617                     {
    618                         COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
    619                         COUT(1) << "Error: Couldn't fabricate a new Object - Identifier is undefined." << std::endl;
    620                         COUT(1) << "Aborting..." << std::endl;
    621                     }
    622 
    623                     assert(false);
    624                     return 0;
    625                 }
    626             }
    627 
    628             /** @brief Returns the assigned identifier. @return The identifier */
    629             inline Identifier* getIdentifier() const
    630                 { return this->identifier_; }
    631 
    632 //            /** @brief Returns true, if the assigned identifier is at least of the given type. @param identifier The identifier to compare with */
    633 //            inline bool isA(const Identifier* identifier) const
    634 //                { return this->identifier_->isA(identifier); }
    635 //
    636 //            /** @brief Returns true, if the assigned identifier is exactly of the given type. @param identifier The identifier to compare with */
    637 //            inline bool isExactlyA(const Identifier* identifier) const
    638 //                { return this->identifier_->isExactlyA(identifier); }
    639 //
    640 //            /** @brief Returns true, if the assigned identifier is a child of the given identifier. @param identifier The identifier to compare with */
    641 //            inline bool isChildOf(const Identifier* identifier) const
    642 //                { return this->identifier_->isChildOf(identifier); }
    643 //
    644 //            /** @brief Returns true, if the assigned identifier is a direct child of the given identifier. @param identifier The identifier to compare with */
    645 //            inline bool isDirectChildOf(const Identifier* identifier) const
    646 //                { return this->identifier_->isDirectChildOf(identifier); }
    647 //
    648 //            /** @brief Returns true, if the assigned identifier is a parent of the given identifier. @param identifier The identifier to compare with */
    649 //            inline bool isParentOf(const Identifier* identifier) const
    650 //                { return this->identifier_->isParentOf(identifier); }
    651 //
    652 //            /** @brief Returns true, if the assigned identifier is a direct parent of the given identifier. @param identifier The identifier to compare with */
    653 //            inline bool isDirectParentOf(const Identifier* identifier) const
    654 //                { return this->identifier_->isDirectParentOf(identifier); }
    655 
    656         private:
    657             Identifier* identifier_;            //!< The assigned identifier
    658     };
    659514}
    660515
  • code/trunk/src/libraries/core/Iterator.h

    r5738 r5929  
    167167
    168168                return (*this);
    169                 return *this;
    170169            }
    171170
     
    193192            inline const Iterator<T>& operator++()
    194193            {
    195                 if (this->element_)
    196                     this->element_ = this->element_->next_;
     194                this->element_ = this->element_->next_;
    197195                return *this;
    198196            }
     
    205203            {
    206204                Iterator<T> copy = *this;
    207                 if (this->element_)
    208                     this->element_ = this->element_->next_;
     205                this->element_ = this->element_->next_;
    209206                return copy;
    210207            }
     
    216213            inline const Iterator<T>& operator--()
    217214            {
    218                 if (this->element_)
    219                     this->element_ = this->element_->prev_;
     215                this->element_ = this->element_->prev_;
    220216                return *this;
    221217            }
     
    228224            {
    229225                Iterator<T> copy = *this;
    230                 if (this->element_)
    231                     this->element_ = this->element_->prev_;
     226                this->element_ = this->element_->prev_;
    232227                return copy;
    233228            }
     
    239234            inline T* operator*() const
    240235            {
    241                 if (this->element_)
    242                     return orxonox_cast<T*>(this->element_->objectBase_);
    243                 else
    244                     return 0;
     236                return orxonox_cast<T*>(this->element_->objectBase_);
    245237            }
    246238
     
    251243            inline T* operator->() const
    252244            {
    253                 if (this->element_)
    254                     return orxonox_cast<T*>(this->element_->objectBase_);
    255                 else
    256                     return 0;
     245                return orxonox_cast<T*>(this->element_->objectBase_);
    257246            }
    258247
  • code/trunk/src/libraries/core/Language.cc

    r5738 r5929  
    3535
    3636#include <fstream>
    37 #include <boost/filesystem.hpp>
    38 
    3937#include "util/Debug.h"
    4038#include "Core.h"
     39#include "PathConfig.h"
    4140
    4241namespace orxonox
     
    200199        COUT(4) << "Read default language file." << std::endl;
    201200
    202         boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
     201        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
    203202
    204203        // This creates the file if it's not existing
    205204        std::ofstream createFile;
    206         createFile.open(filepath.string().c_str(), std::fstream::app);
     205        createFile.open(filepath.c_str(), std::fstream::app);
    207206        createFile.close();
    208207
    209208        // Open the file
    210209        std::ifstream file;
    211         file.open(filepath.string().c_str(), std::fstream::in);
     210        file.open(filepath.c_str(), std::fstream::in);
    212211
    213212        if (!file.is_open())
     
    249248        COUT(4) << "Read translated language file (" << Core::getLanguage() << ")." << std::endl;
    250249
    251         boost::filesystem::path filepath(Core::getConfigPath() / getFilename(Core::getLanguage()));
     250        std::string filepath = PathConfig::getConfigPathString() + getFilename(Core::getLanguage());
    252251
    253252        // Open the file
    254253        std::ifstream file;
    255         file.open(filepath.string().c_str(), std::fstream::in);
     254        file.open(filepath.c_str(), std::fstream::in);
    256255
    257256        if (!file.is_open())
     
    303302        COUT(4) << "Language: Write default language file." << std::endl;
    304303
    305         boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
     304        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
    306305
    307306        // Open the file
    308307        std::ofstream file;
    309         file.open(filepath.string().c_str(), std::fstream::out);
     308        file.open(filepath.c_str(), std::fstream::out);
    310309
    311310        if (!file.is_open())
  • code/trunk/src/libraries/core/Loader.cc

    r5781 r5929  
    103103        {
    104104            if (mask.isIncluded(it->getIdentifier()))
    105                 delete (*(it++));
     105                (it++)->destroy();
    106106            else
    107107                ++it;
     
    204204        {
    205205            if ((it->getFile() == file) && mask.isIncluded(it->getIdentifier()))
    206                 delete (*(it++));
     206                (it++)->destroy();
    207207            else
    208208                ++it;
  • code/trunk/src/libraries/core/LuaState.cc

    r5781 r5929  
    3737
    3838#include "util/Debug.h"
    39 #include "Core.h"
    4039#include "Resource.h"
    4140#include "ToluaBindCore.h"
  • code/trunk/src/libraries/core/MemoryArchive.cc

    r5781 r5929  
    6868                continue;
    6969            if (bDirs)
    70                 file = file.parent_path();
     70                file = file.branch_path();
    7171            if (file.empty())
    7272                continue;
    73             if (file.has_parent_path() && !bRecursive)
     73            if (file.has_branch_path() && !bRecursive)
    7474                continue;
    7575            if (simpleList)
     
    8080                fi.archive = this;
    8181                fi.filename = file.string();
    82                 fi.basename = file.filename();
    83                 fi.path = file.parent_path().string();
     82                fi.basename = file.leaf();
     83                fi.path = file.branch_path().string();
    8484                fi.compressedSize = it->second.second;
    8585                fi.uncompressedSize = it->second.second;
     
    119119
    120120    bool MemoryArchive::exists(const String& filename)
    121         {
     121    {
    122122        const FileMap& files = archives_s[this->getName()];
    123123        return files.find(filename) != files.end();
    124         }
     124    }
    125125
    126126    const Ogre::String& MemoryArchiveFactory::getType(void) const
  • code/trunk/src/libraries/core/ObjectListIterator.h

    r5738 r5929  
    123123            inline const ObjectListIterator<T>& operator++()
    124124            {
    125                 if (this->element_)
    126                     this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
     125                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
    127126                return *this;
    128127            }
     
    135134            {
    136135                ObjectListIterator<T> copy = *this;
    137                 if (this->element_)
    138                     this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
     136                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
    139137                return copy;
    140138            }
     
    146144            inline const ObjectListIterator<T>& operator--()
    147145            {
    148                 if (this->element_)
    149                     this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
     146                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
    150147                return *this;
    151148            }
     
    158155            {
    159156                ObjectListIterator<T> copy = *this;
    160                 if (this->element_)
    161                     this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
     157                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
    162158                return copy;
    163159            }
     
    169165            inline T* operator*() const
    170166            {
    171                 if (this->element_)
    172                     return this->element_->object_;
    173                 else
    174                     return 0;
     167                return this->element_->object_;
    175168            }
    176169
     
    181174            inline T* operator->() const
    182175            {
    183                 if (this->element_)
    184                     return this->element_->object_;
    185                 else
    186                     return 0;
     176                return this->element_->object_;
    187177            }
    188178
  • code/trunk/src/libraries/core/OrxonoxClass.cc

    r5738 r5929  
    3636#include "MetaObjectList.h"
    3737#include "Identifier.h"
     38#include "WeakPtr.h"
    3839
    3940namespace orxonox
     
    4546        this->parents_ = 0;
    4647        this->metaList_ = new MetaObjectList();
     48        this->referenceCount_ = 0;
     49        this->requestedDestruction_ = false;
    4750    }
    4851
     
    5053    OrxonoxClass::~OrxonoxClass()
    5154    {
     55//        if (!this->requestedDestruction_)
     56//            COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ")" << std::endl;
     57
     58        assert(this->referenceCount_ <= 0);
     59
    5260        delete this->metaList_;
    5361
     
    5563        if (this->parents_)
    5664            delete this->parents_;
     65           
     66        // reset all weak pointers pointing to this object
     67        for (std::set<WeakPtr<OrxonoxClass>*>::iterator it = this->weakPointers_.begin(); it != this->weakPointers_.end(); )
     68            (*(it++))->objectDeleted();
     69    }
     70
     71    /** @brief Deletes the object if no smart pointers point to this object. Otherwise schedules the object to be deleted as soon as possible. */
     72    void OrxonoxClass::destroy()
     73    {
     74        this->requestedDestruction_ = true;
     75        if (this->referenceCount_ == 0)
     76            delete this;
    5777    }
    5878
     
    7898
    7999    /** @brief Returns true if the objects class is of the given type or a derivative. */
    80     template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B>* identifier)
    81         { return this->getIdentifier()->isA(identifier->getIdentifier()); }
    82     /** @brief Returns true if the objects class is exactly of the given type. */
    83     template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B>* identifier)
    84         { return this->getIdentifier()->isExactlyA(identifier->getIdentifier()); }
    85     /** @brief Returns true if the objects class is a child of the given type. */
    86     template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B>* identifier)
    87         { return this->getIdentifier()->isChildOf(identifier->getIdentifier()); }
    88     /** @brief Returns true if the objects class is a direct child of the given type. */
    89     template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B>* identifier)
    90         { return this->getIdentifier()->isDirectChildOf(identifier->getIdentifier()); }
    91     /** @brief Returns true if the objects class is a parent of the given type. */
    92     template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B>* identifier)
    93         { return this->getIdentifier()->isParentOf(identifier->getIdentifier()); }
    94     /** @brief Returns true if the objects class is a direct parent of the given type. */
    95     template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B>* identifier)
    96         { return this->getIdentifier()->isDirectParentOf(identifier->getIdentifier()); }
    97 
    98 
    99     /** @brief Returns true if the objects class is of the given type or a derivative. */
    100     template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B> identifier)
    101         { return this->getIdentifier()->isA(identifier.getIdentifier()); }
    102     /** @brief Returns true if the objects class is exactly of the given type. */
    103     template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B> identifier)
    104         { return this->getIdentifier()->isExactlyA(identifier.getIdentifier()); }
    105     /** @brief Returns true if the objects class is a child of the given type. */
    106     template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B> identifier)
    107         { return this->getIdentifier()->isChildOf(identifier.getIdentifier()); }
    108     /** @brief Returns true if the objects class is a direct child of the given type. */
    109     template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B> identifier)
    110         { return this->getIdentifier()->isDirectChildOf(identifier.getIdentifier()); }
    111     /** @brief Returns true if the objects class is a parent of the given type. */
    112     template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B> identifier)
    113         { return this->getIdentifier()->isParentOf(identifier.getIdentifier()); }
    114     /** @brief Returns true if the objects class is a direct parent of the given type. */
    115     template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B> identifier)
    116         { return this->getIdentifier()->isDirectParentOf(identifier.getIdentifier()); }
    117 
    118 
    119     /** @brief Returns true if the objects class is of the given type or a derivative. */
    120100    bool OrxonoxClass::isA(const OrxonoxClass* object)
    121101        { return this->getIdentifier()->isA(object->getIdentifier()); }
  • code/trunk/src/libraries/core/OrxonoxClass.h

    r5738 r5929  
    5555        friend class ClassIdentifier;
    5656
     57        template <class T>
     58        friend class SmartPtr;
     59
     60        template <class T>
     61        friend class WeakPtr;
     62
    5763        public:
    5864            OrxonoxClass();
    5965            virtual ~OrxonoxClass();
     66
     67            void destroy();
    6068
    6169            /** @brief Function to collect the SetConfigValue-macro calls. */
     
    7280            bool isDirectParentOf(const Identifier* identifier);
    7381
    74             template <class B> bool isA(const SubclassIdentifier<B>* identifier);
    75             template <class B> bool isExactlyA(const SubclassIdentifier<B>* identifier);
    76             template <class B> bool isChildOf(const SubclassIdentifier<B>* identifier);
    77             template <class B> bool isDirectChildOf(const SubclassIdentifier<B>* identifier);
    78             template <class B> bool isParentOf(const SubclassIdentifier<B>* identifier);
    79             template <class B> bool isDirectParentOf(const SubclassIdentifier<B>* identifier);
    80 
    81             template <class B> bool isA(const SubclassIdentifier<B> identifier);
    82             template <class B> bool isExactlyA(const SubclassIdentifier<B> identifier);
    83             template <class B> bool isChildOf(const SubclassIdentifier<B> identifier);
    84             template <class B> bool isDirectChildOf(const SubclassIdentifier<B> identifier);
    85             template <class B> bool isParentOf(const SubclassIdentifier<B> identifier);
    86             template <class B> bool isDirectParentOf(const SubclassIdentifier<B> identifier);
     82            template <class B> inline bool isA(const SubclassIdentifier<B>* identifier)
     83                { return this->isA(*identifier); }
     84            template <class B> inline bool isExactlyA(const SubclassIdentifier<B>* identifier)
     85                { return this->isExactlyA(*identifier); }
     86            template <class B> inline bool isChildOf(const SubclassIdentifier<B>* identifier)
     87                { return this->isChildOf(*identifier); }
     88            template <class B> inline bool isDirectChildOf(const SubclassIdentifier<B>* identifier)
     89                { return this->isDirectChildOf(*identifier); }
     90            template <class B> inline bool isParentOf(const SubclassIdentifier<B>* identifier)
     91                { return this->isParentOf(*identifier); }
     92            template <class B> inline bool isDirectParentOf(const SubclassIdentifier<B>* identifier)
     93                { return this->isDirectParentOf(*identifier); }
    8794
    8895            bool isA(const OrxonoxClass* object);
     
    93100            bool isDirectParentOf(const OrxonoxClass* object);
    94101
     102            inline unsigned int getReferenceCount() const
     103                { return this->referenceCount_; }
     104
    95105            /**
    96106            @brief
     
    100110                Returns NULL if the no pointer was found.
    101111            */
    102             template <class T>
    103             FORCEINLINE T* getDerivedPointer(unsigned int classID)
     112            FORCEINLINE void* getDerivedPointer(unsigned int classID)
    104113            {
    105114                for (int i = this->objectPointers_.size() - 1; i >= 0; --i)
    106115                {
    107116                    if (this->objectPointers_[i].first == classID)
    108                         return static_cast<T*>(this->objectPointers_[i].second);
     117                        return this->objectPointers_[i].second;
    109118                }
    110119                return NULL;
    111120            }
    112             //! Const version of getDerivedPointer
    113             template <class T>
    114             FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
    115             {
    116                 return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);
    117             }
     121
     122            //! Version of getDerivedPointer with template
     123            template <class T> FORCEINLINE T* getDerivedPointer(unsigned int classID)
     124            {   return static_cast<T*>(this->getDerivedPointer(classID));   }
     125            //! Const version of getDerivedPointer with template
     126            template <class T> FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
     127            {   return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);   }
    118128
    119129        private:
     130            /** @brief Increments the reference counter (for smart pointers). */
     131            inline void incrementReferenceCount()
     132                { ++this->referenceCount_; }
     133            /** @brief Decrements the reference counter (for smart pointers). */
     134            inline void decrementReferenceCount()
     135                { --this->referenceCount_; if (this->referenceCount_ == 0 && this->requestedDestruction_) { delete this; } }
     136               
     137            /** @brief Register a weak pointer which points to this object. */
     138            template <class T>
     139            inline void registerWeakPtr(WeakPtr<T>* pointer)
     140                { this->weakPointers_.insert(reinterpret_cast<WeakPtr<OrxonoxClass>*>(pointer)); }
     141            /** @brief Unegister a weak pointer which pointed to this object before. */
     142            template <class T>
     143            inline void unregisterWeakPtr(WeakPtr<T>* pointer)
     144                { this->weakPointers_.erase(reinterpret_cast<WeakPtr<OrxonoxClass>*>(pointer)); }
     145
    120146            Identifier* identifier_;                   //!< The Identifier of the object
    121147            std::set<const Identifier*>* parents_;     //!< List of all parents of the object
    122148            MetaObjectList* metaList_;                 //!< MetaObjectList, containing all ObjectLists and ObjectListElements the object is registered in
     149            int referenceCount_;                       //!< Counts the references from smart pointers to this object
     150            bool requestedDestruction_;                //!< Becomes true after someone called delete on this object
     151            std::set<WeakPtr<OrxonoxClass>*> weakPointers_; //!< All weak pointers which point to this object (and like to get notified if it dies)
     152
    123153            //! 'Fast map' that holds this-pointers of all derived types
    124154            std::vector<std::pair<unsigned int, void*> > objectPointers_;
  • code/trunk/src/libraries/core/Resource.h

    r5781 r5929  
    6464        // Docs by Ogre::ResourceGroupManager.h
    6565    public:
    66                 /**
     66        /**
    6767        @brief
    6868            Open a single resource by name and return a DataStream
     
    8181            Shared pointer to data stream containing the data. Will be
    8282            destroyed automatically when no longer referenced.
    83                 */
     83        */
    8484        static DataStreamPtr open(const std::string& name,
    8585            const std::string& group = Resource::DEFAULT_GROUP,
    8686            bool bSearchGroupsIfNotFound = false);
    8787
    88                 /**
     88        /**
    8989        @brief
    9090            Open all resources matching a given pattern (which can contain
     
    101101            Shared pointer to a data stream list , will be
    102102            destroyed automatically when no longer referenced
    103                 */
     103        */
    104104        static DataStreamListPtr openMulti(const std::string& pattern, const std::string& group = Resource::DEFAULT_GROUP);
    105105
  • code/trunk/src/libraries/core/Shell.cc

    r5781 r5929  
    8888        OutputHandler::getOutStream().setOutputBuffer(0);
    8989        if (this->inputBuffer_)
    90             delete this->inputBuffer_;
     90            this->inputBuffer_->destroy();
    9191    }
    9292
  • code/trunk/src/libraries/core/Super.h

    r5781 r5929  
    250250        SUPER_NOARGS(classname, functionname)
    251251
    252     #define SUPER_processEvent(classname, functionname, ...) \
     252    #define SUPER_XMLEventPort(classname, functionname, ...) \
    253253        SUPER_ARGS(classname, functionname, __VA_ARGS__)
    254254
    255255    #define SUPER_changedScale(classname, functionname, ...) \
    256         SUPER_NOARGS(classname, functionname)
    257 
    258     #define SUPER_changedMainState(classname, functionname, ...) \
    259256        SUPER_NOARGS(classname, functionname)
    260257
     
    497494        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    498495
    499         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, processEvent, true, Event& event)
    500             (event)
     496        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, XMLEventPort, true, Element& xmlelement, XMLPort::Mode mode)
     497            (xmlelement, mode)
    501498        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    502499
     
    505502        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    506503
    507         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedMainState, false)
    508             ()
    509         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    510 
    511         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOwner, false)
    512             ()
    513         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    514 
    515         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedOverlayGroup, false)
    516             ()
    517         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    518 
    519         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedName, false)
    520             ()
    521         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
    522 
    523         SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(10, changedGametype, false)
     504        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedOwner, false)
     505            ()
     506        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
     507
     508        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOverlayGroup, false)
     509            ()
     510        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
     511
     512        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedName, false)
     513            ()
     514        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
     515
     516        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedGametype, false)
    524517            ()
    525518        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
     
    571564    SUPER_INTRUSIVE_DECLARATION(changedActivity);
    572565    SUPER_INTRUSIVE_DECLARATION(changedVisibility);
    573     SUPER_INTRUSIVE_DECLARATION(processEvent);
     566    SUPER_INTRUSIVE_DECLARATION(XMLEventPort);
    574567    SUPER_INTRUSIVE_DECLARATION(changedScale);
    575     SUPER_INTRUSIVE_DECLARATION(changedMainState);
    576568    SUPER_INTRUSIVE_DECLARATION(changedOwner);
    577569    SUPER_INTRUSIVE_DECLARATION(changedOverlayGroup);
  • code/trunk/src/libraries/core/TclBind.cc

    r5781 r5929  
    3939#include "CommandExecutor.h"
    4040#include "ConsoleCommand.h"
    41 #include "Core.h"
     41#include "PathConfig.h"
    4242#include "TclThreadManager.h"
    4343
     
    123123    {
    124124#ifdef DEPENDENCY_PACKAGE_ENABLE
    125         if (Core::isDevelopmentRun())
     125        if (PathConfig::isDevelopmentRun())
    126126            return (std::string(specialConfig::dependencyLibraryDirectory) + "/tcl");
    127127        else
    128             return (Core::getRootPathString() + "lib/tcl");
     128            return (PathConfig::getRootPathString() + "lib/tcl");
    129129#else
    130130        return "";
  • code/trunk/src/libraries/core/TclThreadManager.cc

    r5781 r5929  
    3636#include <cpptcl/cpptcl.h>
    3737
     38#include "util/Clock.h"
    3839#include "util/Convert.h"
    3940#include "util/Exception.h"
    40 #include "Clock.h"
    4141#include "CommandExecutor.h"
    4242#include "ConsoleCommand.h"
  • code/trunk/src/libraries/core/XMLPort.h

    r5781 r5929  
    5151#include "util/MultiType.h"
    5252#include "util/OrxAssert.h"
    53 #include "Factory.h"
    5453#include "Identifier.h"
    5554#include "Executor.h"
     
    377376                            this->owner_->xmlAttributes_.clear();
    378377                            // Iterate through the attributes manually in order to make them case insensitive
    379                             Attribute* attribute = xmlelement.FirstAttribute(false);
     378                            ticpp::Attribute* attribute = xmlelement.FirstAttribute(false);
    380379                            while (attribute != 0)
    381380                            {
     
    412411                    }
    413412                }
    414                 else
     413                else if (mode == XMLPort::SaveObject)
    415414                {
    416415                    if (this->saveexecutor_)
     
    548547                            for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
    549548                            {
    550                                 Identifier* identifier = Factory::getIdentifier(child->Value());
     549                                Identifier* identifier = Identifier::getIdentifierByString(child->Value());
    551550                                if (identifier)
    552551                                {
     
    629628                    }
    630629                }
    631                 else
     630                else if (mode == XMLPort::SaveObject)
    632631                {
    633632                }
  • code/trunk/src/libraries/core/input/Button.cc

    r5781 r5929  
    170170
    171171                // evaluate the command
    172                 CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
     172                const CommandEvaluation& eval = CommandExecutor::evaluate(commandStr);
    173173                if (!eval.isValid())
    174174                {
    175                     parseError("Command evaluation failed.", true);
     175                    parseError("Command evaluation of \"" + commandStr + "\"failed.", true);
    176176                    continue;
    177177                }
  • code/trunk/src/libraries/core/input/CMakeLists.txt

    r5781 r5929  
    99  JoyStickQuantityListener.cc
    1010  KeyBinder.cc
     11  KeyBinderManager.cc
    1112  Keyboard.cc
    1213  KeyDetector.cc
  • code/trunk/src/libraries/core/input/InputDevice.h

    r5781 r5929  
    4141#include <ois/OISInputManager.h>
    4242
     43#include "util/Clock.h"
    4344#include "util/Debug.h"
    4445#include "util/Exception.h"
    45 #include "core/Clock.h"
    4646#include "InputState.h"
    4747
  • code/trunk/src/libraries/core/input/InputManager.cc

    r5781 r5929  
    4141#include <boost/foreach.hpp>
    4242
     43#include "util/Clock.h"
    4344#include "util/Convert.h"
    4445#include "util/Exception.h"
    4546#include "util/ScopeGuard.h"
    46 #include "core/Clock.h"
    4747#include "core/CoreIncludes.h"
    4848#include "core/ConfigValueIncludes.h"
     
    5353
    5454#include "InputBuffer.h"
    55 #include "KeyDetector.h"
    5655#include "JoyStick.h"
    5756#include "JoyStickQuantityListener.h"
     
    8887        , oisInputManager_(0)
    8988        , devices_(2)
    90         , bExclusiveMouse_(false)
     89        , mouseMode_(MouseMode::Nonexclusive)
    9190        , emptyState_(0)
    92         , keyDetector_(0)
    9391        , calibratorCallbackHandler_(0)
    9492    {
     
    9997        this->setConfigValues();
    10098
     99        if (GraphicsManager::getInstance().isFullScreen())
     100            mouseMode_ = MouseMode::Exclusive;
    101101        this->loadDevices();
    102102
     
    105105        emptyState_->setHandler(&InputHandler::EMPTY);
    106106        activeStates_[emptyState_->getPriority()] = emptyState_;
    107 
    108         // KeyDetector to evaluate a pressed key's name
    109         InputState* detector = createInputState("detector", false, false, InputStatePriority::Detector);
    110         // Create a callback to avoid buttonHeld events after the key has been detected
    111         FunctorMember<InputManager>* bufferFunctor = createFunctor(&InputManager::clearBuffers);
    112         bufferFunctor->setObject(this);
    113         detector->setLeaveFunctor(bufferFunctor);
    114         keyDetector_ = new KeyDetector();
    115         detector->setHandler(keyDetector_);
    116107
    117108        // Joy stick calibration helper callback
     
    124115        this->updateActiveStates();
    125116
    126         {
    127             // calibrate console command
    128             FunctorMember<InputManager>* functor = createFunctor(&InputManager::calibrate);
    129             functor->setObject(this);
    130             this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "calibrate"), true);
    131         }
    132         {
    133             // reload console command
    134             FunctorMember<InputManager>* functor = createFunctor(&InputManager::reload);
    135             functor->setObject(this);
    136             this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "reload"), false);
    137         }
     117        // calibrate console command
     118        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::calibrate, this), "calibrate"), true);
     119        // reload console command
     120        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::reload, this), "reload"), false);
    138121
    139122        CCOUT(4) << "Construction complete." << std::endl;
     
    172155        paramList.insert(std::make_pair("w32_keyboard", "DISCL_FOREGROUND"));
    173156        paramList.insert(std::make_pair("w32_mouse", "DISCL_FOREGROUND"));
    174         if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
     157        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
    175158        {
    176159            // Disable Windows key plus special keys (like play, stop, next, etc.)
     
    185168        paramList.insert(std::make_pair("XAutoRepeatOn", "true"));
    186169
    187         if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
     170        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
    188171        {
    189172            if (CommandLine::getValue("keyboard_no_grab").getBool())
     
    274257    }
    275258
    276     void InputManager::setKeyDetectorCallback(const std::string& command)
    277     {
    278         this->keyDetector_->setCallbackCommand(command);
    279     }
    280 
    281259    // ############################################################
    282260    // #####                    Destruction                   #####
     
    289267
    290268        // Destroy calibrator helper handler and state
    291         delete keyDetector_;
    292269        this->destroyState("calibrator");
    293270        // Destroy KeyDetector and state
    294         delete calibratorCallbackHandler_;
    295         this->destroyState("detector");
     271        calibratorCallbackHandler_->destroy();
    296272        // destroy the empty InputState
    297273        this->destroyStateInternal(this->emptyState_);
     
    528504
    529505        // Check whether we have to change the mouse mode
     506        MouseMode::Value requestedMode = MouseMode::Dontcare;
    530507        std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
    531         if (mouseStates.empty() && bExclusiveMouse_ ||
    532             !mouseStates.empty() && mouseStates.front()->getIsExclusiveMouse() != bExclusiveMouse_)
    533         {
    534             bExclusiveMouse_ = !bExclusiveMouse_;
     508        if (mouseStates.empty())
     509            requestedMode = MouseMode::Nonexclusive;
     510        else
     511            requestedMode = mouseStates.front()->getMouseMode();
     512        if (requestedMode != MouseMode::Dontcare && mouseMode_ != requestedMode)
     513        {
     514            mouseMode_ = requestedMode;
    535515            if (!GraphicsManager::getInstance().isFullScreen())
    536516                this->reloadInternal();
     
    722702        }
    723703        statesByName_.erase(state->getName());
    724         delete state;
     704        state->destroy();
    725705    }
    726706}
  • code/trunk/src/libraries/core/input/InputManager.h

    r5781 r5929  
    161161        // Various getters and setters
    162162        //-------------------------------
    163         //! Sets the the name of the command used by the KeyDetector as callback.
    164         void setKeyDetectorCallback(const std::string& command);
    165163        //! Returns the number of joy stick that have been created since the c'tor or last call to reload().
    166164        unsigned int getJoyStickQuantity() const
     
    193191        OIS::InputManager*                  oisInputManager_;      //!< OIS input manager
    194192        std::vector<InputDevice*>           devices_;              //!< List of all input devices (keyboard, mouse, joy sticks)
    195         bool                                bExclusiveMouse_;      //!< Currently applied mouse mode
     193        MouseMode::Value                    mouseMode_;            //!< Currently applied mouse mode
    196194
    197195        // some internally handled states and handlers
    198196        InputState*                         emptyState_;           //!< Lowest priority states (makes handling easier)
    199         KeyDetector*                        keyDetector_;          //!< KeyDetector instance
    200197        //! InputBuffer that reacts to the Enter key when calibrating the joy sticks
    201198        InputBuffer*                        calibratorCallbackHandler_;
  • code/trunk/src/libraries/core/input/InputState.cc

    r5781 r5929  
    3737        , bAlwaysGetsInput_(bAlwaysGetsInput)
    3838        , bTransparent_(bTransparent)
    39         , bExclusiveMouse_(true)
     39        , mouseMode_(MouseMode::Dontcare)
    4040        , bExpired_(true)
    4141        , handlers_(2)
  • code/trunk/src/libraries/core/input/InputState.h

    r5781 r5929  
    5555        static const int Detector     = HighPriority + 2;
    5656    };
     57
     58    namespace MouseMode
     59    {
     60        enum Value
     61        {
     62            Exclusive,
     63            Nonexclusive,
     64            Dontcare
     65        };
     66    }
    5767
    5868    /**
     
    120130        void setHandler        (InputHandler* handler);
    121131
    122         void setIsExclusiveMouse(bool value) { bExclusiveMouse_ = value; this->bExpired_ = true; }
    123         bool getIsExclusiveMouse() const { return bExclusiveMouse_; }
     132        void setMouseMode(MouseMode::Value value) { mouseMode_ = value; this->bExpired_ = true; }
     133        MouseMode::Value getMouseMode() const { return mouseMode_; }
    124134
    125135        //! Returns the name of the state (which is unique!)
     
    174184        const bool                  bAlwaysGetsInput_;      //!< See class declaration for explanation
    175185        const bool                  bTransparent_;          //!< See class declaration for explanation
    176         bool                        bExclusiveMouse_;       //!< See class declaration for explanation
     186        MouseMode::Value            mouseMode_;             //!< See class declaration for explanation
    177187        int                         priority_;              //!< Current priority (might change)
    178188        bool                        bExpired_;              //!< See hasExpired()
  • code/trunk/src/libraries/core/input/KeyBinder.cc

    r5781 r5929  
    2727 */
    2828
    29 /**
    30  @file
    31  @brief Implementation of the different input handlers.
    32  */
    33 
    3429#include "KeyBinder.h"
    3530
    3631#include "util/Convert.h"
    3732#include "util/Debug.h"
     33#include "util/Exception.h"
    3834#include "core/ConfigValueIncludes.h"
    3935#include "core/CoreIncludes.h"
     
    4844        Constructor that does as little as necessary.
    4945    */
    50     KeyBinder::KeyBinder()
     46    KeyBinder::KeyBinder(const std::string& filename)
    5147        : deriveTime_(0.0f)
     48        , filename_(filename)
    5249    {
    5350        mouseRelative_[0] = 0;
     
    103100        // set them here to use allHalfAxes_
    104101        setConfigValues();
     102
     103        // Load the bindings if filename was given
     104        if (!this->filename_.empty())
     105            this->loadBindings();
    105106    }
    106107
     
    240241    @brief
    241242        Loads the key and button bindings.
    242     @return
    243         True if loading succeeded.
    244     */
    245     void KeyBinder::loadBindings(const std::string& filename)
     243    */
     244    void KeyBinder::loadBindings()
    246245    {
    247246        COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
    248247
    249         if (filename.empty())
    250             return;
    251 
    252         if (this->configFile_ == ConfigFileType::NoType)
    253         {
    254             // Get a new ConfigFileType from the ConfigFileManager
    255             this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
    256         }
    257 
    258         ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
     248        // Get a new ConfigFileType from the ConfigFileManager
     249        this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
     250
     251        ConfigFileManager::getInstance().setFilename(this->configFile_, this->filename_);
    259252
    260253        // Parse bindings and create the ConfigValueContainers if necessary
    261         clearBindings();
    262254        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
    263255            it->second->readConfigValue(this->configFile_);
  • code/trunk/src/libraries/core/input/KeyBinder.h

    r5781 r5929  
    2626 *
    2727 */
    28 
    29 /**
    30 @file
    31 @brief
    32     Different definitions of input processing.
    33 */
    3428
    3529#ifndef _KeyBinder_H__
     
    5347    /**
    5448    @brief
    55         Handles mouse, keyboard and joy stick input while in the actual game mode.
    56         Manages the key bindings.
     49        Maps mouse, keyboard and joy stick input to command strings and executes them.
     50
     51        The bindings are stored in ini-files (like the one for configValues) in the config Path.
     52    @remarks
     53        You cannot change the filename because the KeyBinderManager maps these filenames to the
     54        KeyBinders. If you need to load other bindings, just create a new one.
    5755    */
    5856    class _CoreExport KeyBinder : public InputHandler, public JoyStickQuantityListener
    5957    {
    6058    public:
    61         KeyBinder ();
     59        KeyBinder (const std::string& filename);
    6260        virtual ~KeyBinder();
    6361
    64         void loadBindings(const std::string& filename);
    6562        void clearBindings();
    6663        bool setBinding(const std::string& binding, const std::string& name, bool bTemporary = false);
     64        const std::string& getBindingsFilename()
     65            { return this->filename_; }
    6766        void setConfigValues();
    6867        void resetJoyStickAxes();
    6968
    7069    protected: // functions
     70        void loadBindings();
     71        void buttonThresholdChanged();
     72        void initialiseJoyStickBindings();
     73        void compilePointerLists();
     74        // from JoyStickQuantityListener interface
     75        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
     76
    7177        void allDevicesUpdated(float dt);
    7278        void mouseUpdated(float dt);
     
    7480        // internal
    7581        void tickHalfAxis(HalfAxis& halfAxis);
    76 
    77         void buttonThresholdChanged();
    78         // from JoyStickQuantityListener interface
    79         virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
    80         void initialiseJoyStickBindings();
    81         void compilePointerLists();
    8282
    8383        void buttonPressed (const KeyEvent& evt);
     
    144144        float deriveTime_;
    145145
     146        //! Name of the file used in this KeyBinder (constant!)
     147        const std::string filename_;
    146148        //! Config file used. ConfigFileType::NoType in case of KeyDetector. Also indicates whether we've already loaded.
    147149        ConfigFileType configFile_;
     
    171173    };
    172174
     175
    173176    inline void KeyBinder::buttonPressed (const KeyEvent& evt)
    174177    { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnPress); }
  • code/trunk/src/libraries/core/input/KeyDetector.cc

    r5781 r5929  
    2929#include "KeyDetector.h"
    3030
    31 #include "util/Debug.h"
     31#include "core/ConsoleCommand.h"
    3232#include "core/CoreIncludes.h"
     33#include "core/ScopedSingletonManager.h"
    3334#include "Button.h"
     35#include "InputManager.h"
     36#include "InputState.h"
    3437
    3538namespace orxonox
    3639{
    37     /**
    38     @brief
    39         Constructor
    40     */
     40    std::string KeyDetector::callbackCommand_s = "KeyDetectorKeyPressed";
     41    KeyDetector* KeyDetector::singletonPtr_s = 0;
     42    ManageScopedSingleton(KeyDetector, ScopeID::Graphics, false);
     43
    4144    KeyDetector::KeyDetector()
     45        : KeyBinder("")
    4246    {
    4347        RegisterObject(KeyDetector);
     48
     49        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyDetector::callback,  this), callbackCommand_s));
     50        this->assignCommands();
     51
     52        inputState_ = InputManager::getInstance().createInputState("detector", false, false, InputStatePriority::Detector);
     53        // Create a callback to avoid buttonHeld events after the key has been detected
     54        inputState_->setLeaveFunctor(createFunctor(&InputManager::clearBuffers, &InputManager::getInstance()));
     55        inputState_->setHandler(this);
    4456    }
    4557
    46     /**
    47     @brief
    48         Destructor
    49     */
    5058    KeyDetector::~KeyDetector()
    5159    {
     60        inputState_->setHandler(NULL);
     61        InputManager::getInstance().destroyState("detector");
    5262    }
    5363
    54     /**
    55     @brief
    56         Assigns all the buttons 'command' plus the button's name.
    57     */
    58     void KeyDetector::setCallbackCommand(const std::string& command)
     64    void KeyDetector::assignCommands()
    5965    {
    60         callbackCommand_ = command;
     66        // Assign every button/axis the same command, but with its name as argument
    6167        clearBindings();
    6268        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
    6369        {
    64             it->second->bindingString_ = callbackCommand_ + it->second->groupName_ + "." + it->second->name_;
     70            it->second->bindingString_ = callbackCommand_s + " " + it->second->groupName_ + "." + it->second->name_;
    6571            it->second->parse();
    6672        }
     73    }
     74
     75    void KeyDetector::callback(const std::string& name)
     76    {
     77        // Call the registered function
     78        if (this->callbackFunction_)
     79            (*this->callbackFunction_)(name);
    6780    }
    6881
     
    7083    {
    7184        KeyBinder::JoyStickQuantityChanged(joyStickList);
    72         if (!callbackCommand_.empty())
    73             setCallbackCommand(callbackCommand_);
     85        this->assignCommands();
    7486    }
    7587}
  • code/trunk/src/libraries/core/input/KeyDetector.h

    r5781 r5929  
    3232#include "InputPrereqs.h"
    3333
    34 #include <string>
     34#include "util/Singleton.h"
    3535#include "KeyBinder.h"
    3636
    3737namespace orxonox
    3838{
    39     class _CoreExport KeyDetector : public KeyBinder
     39    class _CoreExport KeyDetector : public KeyBinder, public Singleton<KeyDetector>
    4040    {
     41        friend class Singleton<KeyDetector>;
     42
    4143    public:
    4244        KeyDetector();
    4345        ~KeyDetector();
    44         void setCallbackCommand(const std::string& command);
    45         void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
     46
     47        void setCallback(Functor* function) { this->callbackFunction_ = function; }
    4648
    4749    private:
    48         std::string callbackCommand_;
     50        KeyDetector(const KeyDetector&);
     51
     52        void callback(const std::string& name);
     53        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
     54        void assignCommands();
     55
     56        Functor* callbackFunction_;
     57        InputState* inputState_;
     58        static std::string callbackCommand_s;
     59        static KeyDetector* singletonPtr_s;
    4960    };
    5061}
  • code/trunk/src/libraries/core/input/Mouse.cc

    r5781 r5929  
    4848
    4949#ifdef ORXONOX_PLATFORM_LINUX
    50         {
    51             // Mouse grab console command
    52             FunctorMember<Mouse>* functor = createFunctor(&Mouse::grab);
    53             functor->setObject(this);
    54             this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "grab"), false);
    55         }
    56         {
    57             // Mouse ungrab console command
    58             FunctorMember<Mouse>* functor = createFunctor(&Mouse::ungrab);
    59             functor->setObject(this);
    60             this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "ungrab"), false);
    61         }
     50        // Mouse grab console command
     51        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::grab, this), "grab"), false);
     52        // Mouse ungrab console command
     53        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::ungrab, this), "ungrab"), false);
    6254#endif
    6355    }
  • code/trunk/src/libraries/network/Client.cc

    r5781 r5929  
    4343#include <cassert>
    4444
     45#include "util/Clock.h"
    4546#include "util/Debug.h"
    46 #include "core/Clock.h"
    4747#include "synchronisable/Synchronisable.h"
    4848#include "packet/Chat.h"
    4949#include "packet/Gamestate.h"
    5050#include "FunctionCallManager.h"
     51#include "core/CoreIncludes.h"
     52#include "core/Game.h"
    5153
    5254namespace orxonox
     
    158160    return;
    159161  }
     162 
     163  void Client::connectionClosed()
     164  {
     165    ObjectList<Synchronisable>::iterator it;
     166    for(it = ObjectList<Synchronisable>::begin(); it; )
     167    {
     168      if( it->getSyncMode() != 0x0 )
     169        (it++)->destroy();
     170      else
     171      {
     172        ++it;
     173      }
     174    }
     175    Game::getInstance().popState();
     176    Game::getInstance().popState();
     177  }
    160178
    161179}
  • code/trunk/src/libraries/network/Client.h

    r5781 r5929  
    4545
    4646#include <string>
     47
     48#include "util/UtilPrereqs.h"
    4749#include "ClientConnection.h"
    4850#include "GamestateClient.h"
     
    7274
    7375    void update(const Clock& time);
    74 
     76  protected:
     77    virtual void connectionClosed();
    7578  private:
    7679    Client(const Client& copy); // not used
  • code/trunk/src/libraries/network/ClientConnection.cc

    r5781 r5929  
    118118          case ENET_EVENT_TYPE_DISCONNECT:
    119119            COUT(4) << "received disconnect confirmation from server" << endl;
     120            this->connectionClosed();
    120121            return true;
    121122        }
     
    123124    }
    124125    enet_peer_reset( this->server_ );
     126    this->connectionClosed();
    125127    return false;
    126128  }
     
    133135  }
    134136
    135   void ClientConnection::addClient(ENetEvent* event)
     137  void ClientConnection::addPeer(ENetEvent* event)
    136138  {
    137139    assert(0);
    138140  }
    139   void ClientConnection::disconnectPeer(ENetEvent* event)
     141  void ClientConnection::removePeer(ENetEvent* event)
    140142  {
    141143    this->established_=false;
    142144    COUT(1) << "Received disconnect Packet from Server!" << endl;
    143145        // server closed the connection
     146    this->connectionClosed();
    144147  }
    145148
  • code/trunk/src/libraries/network/ClientConnection.h

    r5781 r5929  
    5353    bool addPacket(ENetPacket *packet);
    5454    inline bool isConnected(){ return this->established_; }
     55  protected:
     56    virtual void connectionClosed()=0;
    5557  private:
    56     virtual void addClient(ENetEvent* event);
    57     virtual void disconnectPeer(ENetEvent* event);
     58    virtual void addPeer(ENetEvent* event);
     59    virtual void removePeer(ENetEvent* event);
    5860   
    5961    bool disconnectConnection();
  • code/trunk/src/libraries/network/ClientConnectionListener.cc

    r5781 r5929  
    3333#include "ClientInformation.h"
    3434
    35 namespace orxonox{
     35namespace orxonox
     36{
     37    ClientConnectionListener::ClientConnectionListener()
     38    {
     39        RegisterRootObject(ClientConnectionListener);
     40    }
    3641
    37   ClientConnectionListener::ClientConnectionListener()
    38   {
    39     RegisterRootObject(ClientConnectionListener);
    40   }
     42    void ClientConnectionListener::broadcastClientConnected(unsigned int clientID)
     43    {
     44        for (ObjectList<ClientConnectionListener>::iterator it = ObjectList<ClientConnectionListener>::begin(); it != ObjectList<ClientConnectionListener>::end(); ++it)
     45            it->clientConnected(clientID);
     46    }
     47   
     48    void ClientConnectionListener::broadcastClientDisconnected(unsigned int clientID)
     49    {
     50        for (ObjectList<ClientConnectionListener>::iterator it = ObjectList<ClientConnectionListener>::begin(); it != ObjectList<ClientConnectionListener>::end(); ++it)
     51            it->clientDisconnected(clientID);
     52    }
    4153
    42   void ClientConnectionListener::getConnectedClients(){
    43     if(GameMode::showsGraphics())
    44       this->clientConnected(0); //server client id
    45     ClientInformation *client = ClientInformation::getBegin();
    46     while(client){
    47       this->clientConnected(client->getID());
    48       client=client->next();
     54    void ClientConnectionListener::getConnectedClients()
     55    {
     56        ClientInformation* client = ClientInformation::getBegin();
     57        while (client)
     58        {
     59            this->clientConnected(client->getID());
     60            client = client->next();
     61        }
    4962    }
    50   }
    51 
    5263}
    5364
  • code/trunk/src/libraries/network/ClientConnectionListener.h

    r5781 r5929  
    3333#include "core/OrxonoxClass.h"
    3434
    35 namespace orxonox{
     35namespace orxonox
     36{
     37    class _NetworkExport ClientConnectionListener : virtual public OrxonoxClass
     38    {
     39        public:
     40            ClientConnectionListener();
     41            virtual ~ClientConnectionListener() {}
     42           
     43            static void broadcastClientConnected(unsigned int clientID);
     44            static void broadcastClientDisconnected(unsigned int clientID);
    3645
    37   class _NetworkExport ClientConnectionListener : virtual public OrxonoxClass
    38   {
    39     friend class Server;
     46            virtual void clientConnected(unsigned int clientID) = 0;
     47            virtual void clientDisconnected(unsigned int clientID) = 0;
    4048
    41   public:
    42     ClientConnectionListener();
    43     virtual ~ClientConnectionListener() {}
    44 
    45     void getConnectedClients();
    46 
    47   protected:
    48     virtual void clientConnected(unsigned int clientID) = 0;
    49     virtual void clientDisconnected(unsigned int clientID) = 0;
    50   };
    51 
     49        protected:
     50            void getConnectedClients();
     51    };
    5252}
    5353
  • code/trunk/src/libraries/network/Connection.cc

    • Property svn:eol-style set to native
    r5781 r5929  
    8383        // log handling ================
    8484        case ENET_EVENT_TYPE_CONNECT:
    85           addClient( &event );
     85          addPeer( &event );
    8686          break;
    8787        case ENET_EVENT_TYPE_DISCONNECT:
    88           disconnectPeer( &event );
     88          removePeer( &event );
    8989          break;
    9090        case ENET_EVENT_TYPE_RECEIVE:
  • code/trunk/src/libraries/network/Connection.h

    • Property svn:eol-style set to native
    r5781 r5929  
    6464   
    6565    int service(ENetEvent* event);
    66     void disconnectPeer(ENetPeer *peer);
     66    virtual void disconnectPeer(ENetPeer *peer);
    6767   
    6868    void processQueue();
    69     virtual void addClient(ENetEvent* event)=0;
    70     virtual void disconnectPeer(ENetEvent* event)=0;
     69    virtual void addPeer(ENetEvent* event)=0;
     70    virtual void removePeer(ENetEvent* event)=0;
    7171    virtual bool processPacket(ENetEvent* event);
    7272   
  • code/trunk/src/libraries/network/GamestateClient.cc

    r5781 r5929  
    108108    ObjectList<Synchronisable>::iterator temp=it;
    109109    ++it;
    110     delete  *temp;
     110    temp->destroy(); // or delete?
    111111  }
    112112
  • code/trunk/src/libraries/network/GamestateManager.cc

    r5781 r5929  
    7777        delete (*it2).second;
    7878    }
    79     delete this->trafficControl_;
     79    this->trafficControl_->destroy();
    8080//     delete this->threadMutex_;
    8181//     delete this->threadPool_;
     
    160160      finishGamestate( cid, &clientGamestates.back(), client, reference );
    161161      //FunctorMember<GamestateManager>* functor =
    162 //       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate) );
    163 //       executor->setObject(this);
     162//       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate, this) );
    164163//       executor->setDefaultValues( cid, &clientGamestates.back(), client, reference );
    165164//       (*static_cast<Executor*>(executor))();
  • code/trunk/src/libraries/network/NetworkFunction.cc

    r5781 r5929  
    6060    std::map<std::string, NetworkFunctionBase*>::iterator it;
    6161    for( it=NetworkFunctionBase::nameMap_.begin(); it!=NetworkFunctionBase::nameMap_.end(); ++it )
    62       delete it->second;
     62      it->second->destroy();
    6363  }
    6464 
  • code/trunk/src/libraries/network/NetworkPrereqs.h

    r5781 r5929  
    2828
    2929/**
    30   @file
    31   @brief Contains all the necessary forward declarations for all classes and structs.
     30@file
     31@brief
     32    Shared library macros, enums, constants and forward declarations for the network library
    3233*/
    3334
     
    4041// Shared library settings
    4142//-----------------------------------------------------------------------
     43
    4244#if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( NETWORK_STATIC_BUILD )
    4345#  ifdef NETWORK_SHARED_BUILD
     
    5759
    5860//-----------------------------------------------------------------------
    59 // Library global contants
     61// Constants
    6062//-----------------------------------------------------------------------
     63
    6164namespace orxonox
    6265{
    6366  static const unsigned int GAMESTATEID_INITIAL = static_cast<unsigned int>(-1);
    6467  static const unsigned int CLIENTID_UNKNOWN    = static_cast<unsigned int>(-2);
    65   static const uint32_t     OBJECTID_UNKNOWN    = static_cast<uint32_t>(-1);
     68}
     69
     70//-----------------------------------------------------------------------
     71// Enums
     72//-----------------------------------------------------------------------
     73
     74namespace orxonox
     75{
     76  namespace packet
     77  {
     78    namespace PacketFlag
     79    {
     80      enum Value
     81      {
     82        Reliable   = 1,
     83        Unsequence = 2,
     84        NoAllocate = 4
     85      };
     86    }
     87  }
    6688}
    6789
     
    84106namespace orxonox
    85107{
     108  class ChatListener;
    86109  class Client;
    87110  class ClientConnection;
    88111  class ClientConnectionListener;
    89   class ClientFrameListener;
    90112  class ClientInformation;
    91113  class Connection;
    92114  class FunctionCallManager;
    93115  class GamestateClient;
     116  class GamestateHandler;
    94117  class GamestateManager;
    95   class GamestateHandler;
    96   class NetworkCallbackBase;
    97   template <class T> class NetworkCallback;
    98   class NetworkCallbackManager;
     118  class Host;
    99119  class NetworkFunctionBase;
     120  struct NetworkFunctionPointer;
    100121  class NetworkFunctionStatic;
     122  template <class T>
     123  class NetworkMemberFunction;
    101124  class NetworkMemberFunctionBase;
    102   template <class T> class NetworkMemeberFunction;
    103   struct NetworkFunctionPointer;
    104125  class Server;
    105126  class ServerConnection;
    106   class ServerFrameListener;
    107   class Synchronisable;
    108   class SynchronisableVariableBase;
    109   template <class T> class SynchronisableVariable;
    110   template <class T> class SynchronisableVariableBidirectional;
    111   struct ClientList;
    112   struct PacketEnvelope;
    113   struct QueueItem;
    114   struct syncData;
    115127  class TrafficControl;
    116   class obj;
    117   class objInfo;
    118128
     129  // packet
    119130  namespace packet
    120131  {
     
    122133    class Chat;
    123134    class ClassID;
     135    class DeleteObjects;
    124136    class FunctionCalls;
    125137    class FunctionIDs;
    126138    class Gamestate;
    127     class NetworkIDs;
    128139    class Packet;
    129140    class Welcome;
     141  }
    130142
    131     namespace PacketFlag
    132     {
    133       enum Value
    134       {
    135         Reliable   = 1,
    136         Unsequence = 2,
    137         NoAllocate = 4
    138       };
    139     }
    140   }
     143  // synchronisable
     144  template <class T>
     145  class NetworkCallback;
     146  class NetworkCallbackBase;
     147  class NetworkCallbackManager;
     148  class Synchronisable;
     149  class SynchronisableHeader;
     150  template <class T>
     151  class SynchronisableVariable;
     152  class SynchronisableVariableBase;
     153  template <class T>
     154  class SynchronisableVariableBidirectional;
    141155}
    142156
  • code/trunk/src/libraries/network/Server.cc

    r5781 r5929  
    4646#include <string>
    4747
     48#include "util/Clock.h"
    4849#include "util/Debug.h"
    49 #include "core/Clock.h"
    5050#include "core/ObjectList.h"
    5151#include "core/Executor.h"
     
    245245    packet::DeleteObjects *del = new packet::DeleteObjects();
    246246    if(!del->fetchIDs())
     247    {
     248      delete del;
    247249      return true;  //everything ok (no deletes this tick)
     250    }
    248251//     COUT(3) << "sending DeleteObjects" << std::endl;
    249252    while(temp != NULL){
     
    267270
    268271
    269   void Server::addClient(ENetEvent *event){
     272  void Server::addPeer(ENetEvent *event){
    270273    static unsigned int newid=1;
    271274
     
    279282
    280283    // inform all the listeners
    281     ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
    282     while(listener){
    283       listener->clientConnected(newid);
    284       listener++;
    285     }
     284    ClientConnectionListener::broadcastClientConnected(newid);
    286285
    287286    ++newid;
     
    290289    createClient(temp->getID());
    291290}
     291
     292  void Server::removePeer(ENetEvent *event)
     293  {
     294    COUT(4) << "removing client from list" << std::endl;
     295    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
     296    if(!client)
     297      return;
     298    else
     299    {
     300      //ServerConnection::disconnectClient( client );
     301      ClientConnectionListener::broadcastClientDisconnected( client->getID() );
     302      delete client;
     303    }
     304  }
    292305
    293306  bool Server::createClient(int clientID){
     
    329342    ServerConnection::disconnectClient( client );
    330343    GamestateManager::removeClient(client);
    331 // inform all the listeners
    332     ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
    333     while(listener){
    334       listener->clientDisconnected(client->getID());
    335       ++listener;
    336     }
    337     delete client; //remove client from list
     344    // inform all the listeners
     345    ClientConnectionListener::broadcastClientDisconnected(client->getID());
    338346  }
    339347
  • code/trunk/src/libraries/network/Server.h

    r5781 r5929  
    3232#include "NetworkPrereqs.h"
    3333
     34#include "util/UtilPrereqs.h"
    3435#include "core/CorePrereqs.h"
    3536#include "Host.h"
     
    6566    unsigned int playerID(){return 0;}
    6667   
    67     void addClient(ENetEvent *event);
     68    void addPeer(ENetEvent *event);
     69    void removePeer(ENetEvent *event);
     70   
    6871    bool createClient(int clientID);
    6972    void disconnectClient( ClientInformation *client);
  • code/trunk/src/libraries/network/ServerConnection.cc

    • Property svn:eol-style set to native
    r5781 r5929  
    103103  {
    104104    Connection::disconnectPeer( client->getPeer() );
    105     delete client;
    106   }
    107  
    108   void ServerConnection::disconnectPeer( ENetEvent* event )
    109   {
    110     COUT(4) << "removing client from list" << std::endl;
    111     ClientInformation *client = ClientInformation::findClient(&event->peer->address);
    112     if(!client)
    113       return;
    114     else
    115       ServerConnection::disconnectClient( client );
    116105  }
    117106 
     
    119108    ClientInformation *client = ClientInformation::findClient(clientID);
    120109    if(client)
    121       disconnectClient(client);
     110      ServerConnection::disconnectClient(client);
    122111  }
    123112
     
    126115    ClientInformation *temp = ClientInformation::getBegin();
    127116    while(temp!=0){
    128       disconnectClient( temp );
     117      ServerConnection::disconnectClient( temp );
    129118      temp = temp->next();
    130119    }
     
    141130          break;
    142131        case ENET_EVENT_TYPE_DISCONNECT:
    143           if(ClientInformation::findClient(&(event.peer->address)))
    144             delete ClientInformation::findClient(&(event.peer->address));
     132          removePeer( &event );
    145133          temp = ClientInformation::getBegin();
    146134          break;
  • code/trunk/src/libraries/network/ServerConnection.h

    • Property svn:eol-style set to native
    r5781 r5929  
    5959    static bool addPacketAll(ENetPacket *packet);
    6060    virtual void disconnectClient(ClientInformation *client);
    61     void disconnectPeer( ENetEvent* event );
    6261    void disconnectClient(int clientID);
    6362  protected:
  • code/trunk/src/libraries/network/packet/CMakeLists.txt

    r5781 r5929  
    11ADD_SOURCE_FILES(NETWORK_SRC_FILES
     2COMPILATION_BEGIN PacketCompilation.cc
    23  Acknowledgement.cc
    34  Chat.cc
     
    910  Packet.cc
    1011  Welcome.cc
     12COMPILATION_END
    1113)
    1214
  • code/trunk/src/libraries/network/packet/ClassID.cc

    r5781 r5929  
    4949  Identifier *id;
    5050  std::string classname;
    51   unsigned int nrOfClasses=0; 
     51  unsigned int nrOfClasses=0;
    5252  unsigned int packetSize=2*sizeof(uint32_t); //space for the packetID and for the nrofclasses
    5353  uint32_t network_id;
    5454  flags_ = flags_ | PACKET_FLAGS_CLASSID;
    5555  std::queue<std::pair<uint32_t, std::string> > tempQueue;
    56  
     56
    5757  //calculate total needed size (for all strings and integers)
    58   std::map<std::string, Identifier*>::const_iterator it = Factory::getFactoryMapBegin();
    59   for(;it != Factory::getFactoryMapEnd();++it){
     58  std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin();
     59  for(;it != Identifier::getStringIdentifierMapEnd();++it){
    6060    id = (*it).second;
    61     if(id == NULL)
     61    if(id == NULL || !id->hasFactory())
    6262      continue;
    6363    classname = id->getName();
    6464    network_id = id->getNetworkID();
    65     if(network_id==0)
    66       COUT(3) << "we got a null class id: " << id->getName() << std::endl;
    6765    // now push the network id and the classname to the stack
    6866    tempQueue.push( std::pair<unsigned int, std::string>(network_id, classname) );
     
    7068    packetSize += (classname.size()+1)+sizeof(uint32_t)+sizeof(uint32_t);
    7169  }
    72  
     70
    7371  this->data_=new uint8_t[ packetSize ];
    7472  //set the appropriate packet id
    7573  assert(this->data_);
    7674  *(Type::Value *)(this->data_ + _PACKETID ) = Type::ClassID;
    77  
     75
    7876  uint8_t *temp=data_+sizeof(uint32_t);
    7977  // save the number of all classes
    8078  *(uint32_t*)temp = nrOfClasses;
    8179  temp += sizeof(uint32_t);
    82  
     80
    8381  // now save all classids and classnames
    8482  std::pair<uint32_t, std::string> tempPair;
     
    9189    temp+=2*sizeof(uint32_t)+tempPair.second.size()+1;
    9290  }
    93  
     91
    9492  COUT(5) << "classid packetSize is " << packetSize << endl;
    95  
     93
    9694}
    9795
     
    111109  temp += sizeof(uint32_t);
    112110  totalsize += sizeof(uint32_t); // storage size for nr of all classes
    113  
     111
    114112  for(unsigned int i=0; i<nrOfClasses; i++){
    115113    totalsize += 2*sizeof(uint32_t) + *(uint32_t*)(temp + sizeof(uint32_t));
     
    125123  uint32_t stringsize;
    126124  unsigned char *classname;
    127  
    128  
    129   //clean the map of network ids
    130   Factory::cleanNetworkIDs();
    131  
     125
     126
     127  //clear the map of network ids
     128  Identifier::clearNetworkIDs();
     129
    132130  COUT(4) << "=== processing classids: " << endl;
    133131  std::pair<uint32_t, std::string> tempPair;
     
    136134  nrOfClasses = *(uint32_t*)temp;
    137135  temp += sizeof(uint32_t);
    138  
     136
    139137  for( int i=0; i<nrOfClasses; i++){
    140138    networkID = *(uint32_t*)temp;
  • code/trunk/src/libraries/network/packet/Gamestate.cc

    r5781 r5929  
    378378  rawDiff( dest2, dest, basep, header_->getDataSize(), base->header_->getDataSize() );
    379379  assert( memcmp( dest2, gs, dest_length) == 0 );
     380  delete dest2;
    380381#endif
    381382
  • code/trunk/src/libraries/network/synchronisable/Synchronisable.cc

    r5781 r5929  
    4747  /**
    4848  * Constructor:
    49   * Initializes all Variables and sets the right objectID
     49  * Initializes all Variables and sets the right objectID_
    5050  */
    51   Synchronisable::Synchronisable(BaseObject* creator){
     51  Synchronisable::Synchronisable(BaseObject* creator ){
    5252    RegisterRootObject(Synchronisable);
    5353    static uint32_t idCounter=0;
     
    5555    if ( GameMode::isMaster() || ( Host::running() && Host::isServer() ) )
    5656    {
    57       this->objectID = idCounter++; //this is only needed when running a server
    58     //add synchronisable to the objectMap
    59       objectMap_[this->objectID] = this;
     57      this->setObjectID( idCounter++ );
    6058    }
    6159    else
    6260    {
    63       objectID=OBJECTID_UNKNOWN;
    64       this->setObjectMode(0x0);   //make sure this object doesn't get synchronized
    65     }
    66     classID = static_cast<uint32_t>(-1);
     61      objectID_=OBJECTID_UNKNOWN;
     62    }
     63    classID_ = static_cast<uint32_t>(-1);
    6764   
    6865    // set dataSize to 0
     
    7269
    7370    // get creator id
    74     this->creatorID = OBJECTID_UNKNOWN;
    75 
    76     searchcreatorID:
     71    if( creator )
     72      this->creatorID_ = creator->getSceneID();
     73    else
     74      this->creatorID_ = OBJECTID_UNKNOWN;
     75
     76    /*searchcreatorID:
    7777    if (creator)
    7878    {
     
    8080        if (synchronisable_creator && synchronisable_creator->objectMode_)
    8181        {
    82             this->creatorID = synchronisable_creator->getObjectID();
     82            this->creatorID = synchronisable_creator->getScene()->getObjectID();
    8383        }
    8484        else if (creator != creator->getCreator())
     
    8787            goto searchcreatorID;
    8888        }
    89     }
     89    }*/
    9090  }
    9191
    9292  /**
    9393   * Destructor:
    94    * Delete all callback objects and remove objectID from the objectMap_
     94   * Delete all callback objects and remove objectID_ from the objectMap_
    9595   */
    9696  Synchronisable::~Synchronisable(){
     
    9999      // remove object from the static objectMap
    100100      if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
    101         deletedObjects_.push(objectID);
     101        deletedObjects_.push(objectID_);
    102102    }
    103103    // delete all Synchronisable Variables from syncList ( which are also in stringList )
     
    107107    stringList.clear();
    108108    std::map<uint32_t, Synchronisable*>::iterator it;
    109     it = objectMap_.find(objectID);
     109    it = objectMap_.find(objectID_);
    110110    if (it != objectMap_.end())
    111111      objectMap_.erase(it);
     
    172172    Synchronisable *no = orxonox_cast<Synchronisable*>(bo);
    173173    assert(no);
    174     no->objectID=header.getObjectID();
    175     no->creatorID=header.getCreatorID(); //TODO: remove this
    176     no->classID=header.getClassID();
    177     COUT(4) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
     174    assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
     175    no->setObjectID(header.getObjectID());
     176    //no->creatorID=header.getCreatorID(); //TODO: remove this
     177    no->setClassID(header.getClassID());
     178    assert(no->creatorID_ == header.getCreatorID());
     179    //assert(no->classID_ == header.getClassID());
     180    COUT(4) << "fabricate objectID_: " << no->objectID_ << " classID_: " << no->classID_ << std::endl;
    178181          // update data and create object/entity...
    179     assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
    180     Synchronisable::objectMap_[header.getObjectID()] = no;
    181182    bool b = no->updateData(mem, mode, true);
    182183    assert(b);
     
    191192
    192193  /**
    193    * Finds and deletes the Synchronisable with the appropriate objectID
    194    * @param objectID objectID of the Synchronisable
     194   * Finds and deletes the Synchronisable with the appropriate objectID_
     195   * @param objectID_ objectID_ of the Synchronisable
    195196   * @return true/false
    196197   */
    197   bool Synchronisable::deleteObject(uint32_t objectID){
    198     if(!getSynchronisable(objectID))
     198  bool Synchronisable::deleteObject(uint32_t objectID_){
     199    if(!getSynchronisable(objectID_))
    199200      return false;
    200     assert(getSynchronisable(objectID)->objectID==objectID);
    201     Synchronisable *s = getSynchronisable(objectID);
     201    assert(getSynchronisable(objectID_)->objectID_==objectID_);
     202    Synchronisable *s = getSynchronisable(objectID_);
    202203    if(s)
    203       delete s;
     204      s->destroy(); // or delete?
    204205    else
    205206      return false;
     
    208209
    209210  /**
    210    * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
    211    * @param objectID objectID of the Synchronisable
    212    * @return pointer to the Synchronisable with the objectID
    213    */
    214   Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID){
     211   * This function looks up the objectID_ in the objectMap_ and returns a pointer to the right Synchronisable
     212   * @param objectID_ objectID_ of the Synchronisable
     213   * @return pointer to the Synchronisable with the objectID_
     214   */
     215  Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID_){
    215216    std::map<uint32_t, Synchronisable*>::iterator it1;
    216     it1 = objectMap_.find(objectID);
     217    it1 = objectMap_.find(objectID_);
    217218    if (it1 != objectMap_.end())
    218219      return it1->second;
     
    220221//     ObjectList<Synchronisable>::iterator it;
    221222//     for(it = ObjectList<Synchronisable>::begin(); it; ++it){
    222 //       if( it->getObjectID()==objectID ){
    223 //         objectMap_[objectID] = *it;
     223//       if( it->getObjectID()==objectID_ ){
     224//         objectMap_[objectID_] = *it;
    224225//         return *it;
    225226//       }
     
    231232
    232233  /**
    233    * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
     234   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID_ and classID_ to the given memory
    234235   * takes a pointer to already allocated memory (must have at least getSize bytes length)
    235236   * structure of the bitstream:
    236    * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
     237   * |totalsize,objectID_,classID_,var1,var2,string1_length,string1,var3,...|
    237238   * length of varx: size saved int syncvarlist
    238239   * @param mem pointer to allocated memory with enough size
     
    252253    uint32_t tempsize = 0;
    253254#ifndef NDEBUG
    254     if (this->classID==0)
     255    if (this->classID_==0)
    255256      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
    256257#endif
    257258
    258     if (this->classID == static_cast<uint32_t>(-1))
    259         this->classID = this->getIdentifier()->getNetworkID();
    260 
    261     assert(ClassByID(this->classID));
    262     assert(this->classID==this->getIdentifier()->getNetworkID());
     259    if (this->classID_ == static_cast<uint32_t>(-1))
     260        this->classID_ = this->getIdentifier()->getNetworkID();
     261
     262    assert(ClassByID(this->classID_));
     263    assert(this->classID_==this->getIdentifier()->getNetworkID());
     264    assert(this->objectID_!=OBJECTID_UNKNOWN);
    263265    std::vector<SynchronisableVariableBase*>::iterator i;
    264266
     
    269271
    270272
    271     COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << std::endl;
     273    COUT(5) << "Synchronisable getting data from objectID_: " << objectID_ << " classID_: " << classID_ << std::endl;
    272274    // copy to location
    273275    for(i=syncList.begin(); i!=syncList.end(); ++i){
     
    277279   
    278280    tempsize += SynchronisableHeader::getSize();
    279     header.setObjectID( this->objectID );
    280     header.setCreatorID( this->creatorID );
    281     header.setClassID( this->classID );
     281    header.setObjectID( this->objectID_ );
     282    header.setCreatorID( this->creatorID_ );
     283    header.setClassID( this->classID_ );
    282284    header.setDataAvailable( true );
    283285    header.setDataSize( tempsize );
     
    311313    // start extract header
    312314    SynchronisableHeader syncHeader(mem);
    313     assert(syncHeader.getObjectID()==this->objectID);
    314     assert(syncHeader.getCreatorID()==this->creatorID);
    315     assert(syncHeader.getClassID()==this->classID);
     315    assert(syncHeader.getObjectID()==this->objectID_);
     316    assert(syncHeader.getCreatorID()==this->creatorID_);
     317    assert(syncHeader.getClassID()==this->classID_);
    316318    if(syncHeader.isDataAvailable()==false){
    317319      mem += syncHeader.getDataSize();
     
    322324    // stop extract header
    323325
    324     //COUT(5) << "Synchronisable: objectID " << syncHeader.getObjectID() << ", classID " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << std::endl;
     326    //COUT(5) << "Synchronisable: objectID_ " << syncHeader.getObjectID() << ", classID_ " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << std::endl;
    325327    for(i=syncList.begin(); i!=syncList.end(); i++)
    326328    {
     
    361363    if(mode==0x0)
    362364      mode=state_;
    363     return ( (objectMode_&mode)!=0 && (!syncList.empty() ) );
    364   }
    365 
    366   /**
    367    * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
     365    return ( (this->objectMode_ & mode)!=0 && (!syncList.empty() ) );
     366  }
     367
     368  /**
     369   * This function looks at the header located in the bytestream and checks wheter objectID_ and classID_ match with the Synchronisables ones
    368370   * @param mem pointer to the bytestream
    369371   */
     
    371373  {
    372374    SynchronisableHeader header(mem);
    373     assert(header.getObjectID()==this->objectID);
     375    assert(header.getObjectID()==this->objectID_);
    374376    return header.isDataAvailable();
    375377  }
     
    383385   * @param mode same as in registerVar
    384386   */
    385   void Synchronisable::setObjectMode(uint8_t mode){
     387  void Synchronisable::setSyncMode(uint8_t mode){
    386388    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
    387     objectMode_=mode;
     389    this->objectMode_=mode;
    388390  }
    389391
  • code/trunk/src/libraries/network/synchronisable/Synchronisable.h

    r5781 r5929  
    6868   * @brief: stores information about a Synchronisable
    6969   *
    70    * This class stores the information about a Synchronisable (objectID, classID, creatorID, dataSize)
     70   * This class stores the information about a Synchronisable (objectID_, classID_, creatorID_, dataSize)
    7171   * in an emulated bitset.
    7272   * Bit 1 to 31 store the size of the Data the synchronisable consumes in the stream
    7373   * Bit 32 is a bool and defines whether the data is actually stored or is just filled up with 0
    74    * Byte 5 to 8: objectID
    75    * Byte 9 to 12: classID
    76    * Byte 13 to 16: creatorID
     74   * Byte 5 to 8: objectID_
     75   * Byte 9 to 12: classID_
     76   * Byte 13 to 16: creatorID_
    7777   */
    7878  class _NetworkExport SynchronisableHeader{
     
    9494      inline uint32_t getObjectID() const
    9595        { return *(uint32_t*)(data_+4); }
    96       inline void setObjectID(uint32_t objectID)
    97         { *(uint32_t*)(data_+4) = objectID; }
     96      inline void setObjectID(uint32_t objectID_)
     97        { *(uint32_t*)(data_+4) = objectID_; }
    9898      inline uint32_t getClassID() const
    9999        { return *(uint32_t*)(data_+8); }
    100       inline void setClassID(uint32_t classID)
    101         { *(uint32_t*)(data_+8) = classID; }
     100      inline void setClassID(uint32_t classID_)
     101        { *(uint32_t*)(data_+8) = classID_; }
    102102      inline uint32_t getCreatorID() const
    103103        { return *(uint32_t*)(data_+12); }
    104       inline void setCreatorID(uint32_t creatorID)
    105         { *(uint32_t*)(data_+12) = creatorID; }
     104      inline void setCreatorID(uint32_t creatorID_)
     105        { *(uint32_t*)(data_+12) = creatorID_; }
    106106      inline void operator=(SynchronisableHeader& h)
    107107        { memcpy(data_, h.data_, getSize()); }
     
    122122
    123123    static Synchronisable *fabricate(uint8_t*& mem, uint8_t mode=0x0);
    124     static bool deleteObject(uint32_t objectID);
    125     static Synchronisable *getSynchronisable(uint32_t objectID);
     124    static bool deleteObject(uint32_t objectID_);
     125    static Synchronisable *getSynchronisable(uint32_t objectID_);
    126126    static unsigned int getNumberOfDeletedObject(){ return deletedObjects_.size(); }
    127127    static uint32_t popDeletedObject(){ uint32_t i = deletedObjects_.front(); deletedObjects_.pop(); return i; }
    128128
    129     inline uint32_t getObjectID() const {return objectID;}
    130     inline unsigned int getCreatorID() const {return creatorID;}
    131     inline uint32_t getClassID() const {return classID;}
    132     inline unsigned int getPriority() const { return objectFrequency_;}
     129    inline uint32_t getObjectID() const {return this->objectID_;}
     130    inline unsigned int getCreatorID() const {return this->creatorID_;}
     131    inline uint32_t getClassID() const {return this->classID_;}
     132    inline unsigned int getPriority() const { return this->objectFrequency_;}
     133    inline uint8_t getSyncMode() const { return this->objectMode_; }
     134   
     135    void setSyncMode(uint8_t mode);
    133136
    134137  protected:
     
    136139    template <class T> void registerVariable(T& variable, uint8_t mode=0x1, NetworkCallbackBase *cb=0, bool bidirectional=false);
    137140    //template <class T> void unregisterVariable(T& var);
    138     void setObjectMode(uint8_t mode);
    139141    void setPriority(unsigned int freq){ objectFrequency_ = freq; }
    140142
     
    146148    bool isMyData(uint8_t* mem);
    147149    bool doSync(int32_t id, uint8_t mode=0x0);
    148 
    149     uint32_t objectID;
    150     uint32_t creatorID;
    151     uint32_t classID;
     150   
     151    inline void setObjectID(uint32_t id){ this->objectID_ = id; objectMap_[this->objectID_] = this; }
     152    inline void setClassID(uint32_t id){ this->classID_ = id; }
     153
     154    uint32_t objectID_;
     155    uint32_t creatorID_;
     156    uint32_t classID_;
    152157
    153158    std::vector<SynchronisableVariableBase*> syncList;
  • code/trunk/src/libraries/tools/CMakeLists.txt

    r5781 r5929  
    1 ADD_SOURCE_FILES(TOOLS_SRC_FILES
     1SET_SOURCE_FILES(TOOLS_SRC_FILES
     2COMPILATION_BEGIN ResourceCompilation.cc
     3  ResourceCollection.cc
     4  ResourceLocation.cc
     5COMPILATION_END
     6  TextureGenerator.cc
     7  Timer.cc
     8COMPILATION_BEGIN OgreCompilation.cc
    29  BillboardSet.cc
    310  DynamicLines.cc
     
    512  Mesh.cc
    613  ParticleInterface.cc
    7   ResourceCollection.cc
    8   ResourceLocation.cc
    914  Shader.cc
    10   TextureGenerator.cc
    11   Timer.cc
     15COMPILATION_END
    1216)
    1317ADD_SUBDIRECTORY(interfaces)
     
    1519ORXONOX_ADD_LIBRARY(tools
    1620  FIND_HEADER_FILES
    17   PCH_FILE
    18     ToolsPrecompiledHeaders.h
    1921  DEFINE_SYMBOL
    2022    "TOOLS_SHARED_BUILD"
  • code/trunk/src/libraries/tools/ResourceLocation.cc

    r5781 r5929  
    3333
    3434#include "util/Exception.h"
    35 #include "core/Core.h"
    3635#include "core/CoreIncludes.h"
     36#include "core/PathConfig.h"
    3737#include "core/XMLFile.h"
    3838#include "core/XMLPort.h"
     
    7171
    7272        // Find the path
    73         boost::filesystem::path path;
    74         if (boost::filesystem::exists(Core::getDataPath() / this->getPath()))
    75             path = Core::getDataPath() / this->getPath();
    76         else if (Core::isDevelopmentRun() && boost::filesystem::exists(Core::getExternalDataPath() / this->getPath()))
    77             path = Core::getExternalDataPath() / this->getPath();
     73        namespace bf = boost::filesystem;
     74        bf::path path;
     75        if (bf::exists(PathConfig::getDataPath() / this->getPath()))
     76            path = PathConfig::getDataPath() / this->getPath();
     77        else if (PathConfig::isDevelopmentRun() && bf::exists(PathConfig::getExternalDataPath() / this->getPath()))
     78            path = PathConfig::getExternalDataPath() / this->getPath();
    7879        else
    7980        {
  • code/trunk/src/libraries/tools/Timer.cc

    r5781 r5929  
    3131#include <set>
    3232
     33#include "util/Clock.h"
    3334#include "core/CoreIncludes.h"
    3435#include "core/ConsoleCommand.h"
    3536#include "core/CommandExecutor.h"
    36 #include "core/Clock.h"
    3737#include "core/Functor.h"
    3838
     
    4242    SetConsoleCommandShortcutExtern(killdelays);
    4343
    44     static std::set<StaticTimer*> delaytimerset;
     44    static std::set<Timer*> delaytimerset;
    4545
    4646    /**
     
    5151    void delay(float delay, const std::string& command)
    5252    {
    53         StaticTimer *delaytimer = new StaticTimer();
     53        Timer* delaytimer = new Timer();
    5454        delaytimerset.insert(delaytimer);
    5555
     
    6464        @param command The command to execute
    6565    */
    66     void executeDelayedCommand(StaticTimer* timer, const std::string& command)
     66    void executeDelayedCommand(Timer* timer, const std::string& command)
    6767    {
    6868        CommandExecutor::execute(command);
    69         delete timer;
     69        timer->destroy();
    7070        delaytimerset.erase(timer);
    7171    }
     
    7676    void killdelays()
    7777    {
    78         for (std::set<StaticTimer*>::iterator it = delaytimerset.begin(); it != delaytimerset.end(); ++it)
    79             delete (*it);
     78        for (std::set<Timer*>::iterator it = delaytimerset.begin(); it != delaytimerset.end(); ++it)
     79            (*it)->destroy();
    8080
    8181        delaytimerset.clear();
     
    8585        @brief Constructor: Sets the default-values.
    8686    */
    87     TimerBase::TimerBase()
     87    Timer::Timer()
     88    {
     89        this->init();
     90        RegisterObject(Timer);
     91    }
     92
     93    /**
     94        @brief Constructor: Initializes the Timer with given values.
     95        @param interval The timer-interval in seconds
     96        @param bLoop If true, the function gets called every 'interval' seconds
     97        @param exeuctor A executor of the function to call
     98    */
     99    Timer::Timer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall)
     100    {
     101        this->init();
     102        RegisterObject(Timer);
     103
     104        this->setTimer(interval, bLoop, executor, bKillAfterCall);
     105    }
     106
     107    /**
     108        @brief Deletes the executor.
     109    */
     110    Timer::~Timer()
     111    {
     112        this->deleteExecutor();
     113    }
     114   
     115    /**
     116        @brief Initializes the Timer
     117    */
     118    void Timer::init()
    88119    {
    89120        this->executor_ = 0;
     
    94125
    95126        this->time_ = 0;
    96 
    97         RegisterObject(TimerBase);
    98     }
    99 
    100     /**
    101         @brief Deletes the executor.
    102     */
    103     TimerBase::~TimerBase()
    104     {
    105         this->deleteExecutor();
    106127    }
    107128
     
    109130        @brief Executes the executor.
    110131    */
    111     void TimerBase::run() const
     132    void Timer::run()
    112133    {
    113134        bool temp = this->bKillAfterCall_; // to avoid errors with bKillAfterCall_=false and an exutors which destroy the timer
     
    116137
    117138        if (temp)
    118             delete this;
     139            this->destroy();
    119140    }
    120141
     
    122143        @brief Deletes the executor.
    123144    */
    124     void TimerBase::deleteExecutor()
     145    void Timer::deleteExecutor()
    125146    {
    126147      if (this->executor_)
     
    131152        @brief Updates the timer before the frames are rendered.
    132153    */
    133     void TimerBase::tick(const Clock& time)
     154    void Timer::tick(const Clock& time)
    134155    {
    135156        if (this->bActive_)
  • code/trunk/src/libraries/tools/Timer.h

    r5781 r5929  
    4040                ClassName();
    4141                void functionName();
    42                 Timer<ClassName> myTimer;
     42                Timer myTimer;
    4343        };
    4444
     
    4848        ClassName::ClassName()
    4949        {
    50             myTimer.setTimer(interval_in_seconds, bLoop, this, createExecutor(createFunctor(&ClassName::functionName)));
     50            myTimer.setTimer(interval_in_seconds, bLoop, createExecutor(createFunctor(&ClassName::functionName, this)));
    5151        }
    5252
     
    6969namespace orxonox
    7070{
    71     class StaticTimer;
    7271    void delay(float delay, const std::string& command);
    7372    void killdelays();
    74     void executeDelayedCommand(StaticTimer* timer, const std::string& command);
     73    void executeDelayedCommand(Timer* timer, const std::string& command);
    7574
    76     //! TimerBase is the parent of the Timer class.
    77     class _ToolsExport TimerBase : public TimeFactorListener
     75    //! The Timer is a callback-object, calling a given function after a given time-interval.
     76    class _ToolsExport Timer : public TimeFactorListener
    7877    {
    7978        public:
    80             ~TimerBase();
     79            Timer();
     80            ~Timer();
    8181
    82             void run() const;
     82            Timer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall = false);
     83
     84            /**
     85                @brief Initializes the Timer with given values.
     86                @param interval The timer-interval in seconds
     87                @param bLoop If true, the function gets called every 'interval' seconds
     88                @param object The object owning the timer and the function
     89                @param executor A executor of the function to call
     90            */
     91            void setTimer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall = false)
     92            {
     93                this->deleteExecutor();
     94
     95                this->setInterval(interval);
     96                this->bLoop_ = bLoop;
     97                this->executor_ = executor;
     98                this->bActive_ = true;
     99
     100                this->time_ = this->interval_;
     101                this->bKillAfterCall_ = bKillAfterCall;
     102            }
     103
     104            void run();
    83105            void deleteExecutor();
    84106
     
    116138            void tick(const Clock& time);
    117139
    118         protected:
    119             TimerBase();
    120 
     140        private:
     141            void init();
     142       
    121143            Executor* executor_;  //!< The executor of the function that should be called when the time expires
    122144
     
    128150            long long time_;      //!< Internal variable, counting the time till the next function-call
    129151    };
    130 
    131     //! The Timer is a callback-object, calling a given function after a given time-interval.
    132     template <class T = BaseObject>
    133     class Timer : public TimerBase
    134     {
    135         public:
    136             Timer() {}
    137 
    138             /**
    139                 @brief Constructor: Initializes the Timer with given values.
    140                 @param interval The timer-interval in seconds
    141                 @param bLoop If true, the function gets called every 'interval' seconds
    142                 @param object The object owning the timer and the function
    143                 @param exeuctor A executor of the function to call
    144             */
    145             Timer(float interval, bool bLoop, T* object, ExecutorMember<T>* exeuctor, bool bKillAfterCall = false)
    146             {
    147                 this->setTimer(interval, bLoop, object, exeuctor, bKillAfterCall);
    148             }
    149 
    150             /**
    151                 @brief Initializes the Timer with given values.
    152                 @param interval The timer-interval in seconds
    153                 @param bLoop If true, the function gets called every 'interval' seconds
    154                 @param object The object owning the timer and the function
    155                 @param exeuctor A executor of the function to call
    156             */
    157             void setTimer(float interval, bool bLoop, T* object, ExecutorMember<T>* executor, bool bKillAfterCall = false)
    158             {
    159                 this->deleteExecutor();
    160 
    161                 this->setInterval(interval);
    162                 this->bLoop_ = bLoop;
    163                 executor->setObject(object);
    164                 this->executor_ = static_cast<Executor*>(executor);
    165                 this->bActive_ = true;
    166 
    167                 this->time_ = this->interval_;
    168                 this->bKillAfterCall_ = bKillAfterCall;
    169             }
    170     };
    171 
    172     //! The StaticTimer is a callback-object, calling a static function after a given time-interval.
    173     class _ToolsExport StaticTimer : public TimerBase
    174     {
    175         public:
    176             StaticTimer() {}
    177 
    178             /**
    179                 @brief Constructor: Initializes the Timer with given values.
    180                 @param interval The timer-interval in seconds
    181                 @param bLoop If true, the function gets called every 'interval' seconds
    182                 @param exeuctor A executor of the function to call
    183             */
    184             StaticTimer(float interval, bool bLoop, ExecutorStatic* executor, bool bKillAfterCall = false)
    185             {
    186                 this->setTimer(interval, bLoop, executor, bKillAfterCall);
    187             }
    188 
    189             /**
    190                 @brief Initializes the Timer with given values.
    191                 @param interval The timer-interval in seconds
    192                 @param bLoop If true, the function gets called every 'interval' seconds
    193                 @param object The object owning the timer and the function
    194                 @param executor A executor of the function to call
    195             */
    196             void setTimer(float interval, bool bLoop, ExecutorStatic* executor, bool bKillAfterCall = false)
    197             {
    198                 this->deleteExecutor();
    199 
    200                 this->setInterval(interval);
    201                 this->bLoop_ = bLoop;
    202                 this->executor_ = executor;
    203                 this->bActive_ = true;
    204 
    205                 this->time_ = this->interval_;
    206                 this->bKillAfterCall_ = bKillAfterCall;
    207             }
    208     };
    209 
    210152}
    211153
  • code/trunk/src/libraries/tools/ToolsPrereqs.h

    r5781 r5929  
    2828
    2929/**
    30   @file
    31   @brief Contains all the necessary forward declarations for all classes and structs.
     30@file
     31@brief
     32    Shared library macros, enums, constants and forward declarations for the tools module
    3233*/
    3334
     
    4041// Shared library settings
    4142//-----------------------------------------------------------------------
     43
    4244#if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
    4345#  ifdef TOOLS_SHARED_BUILD
     
    5759
    5860//-----------------------------------------------------------------------
    59 // Forward declarations
     61// Enums
    6062//-----------------------------------------------------------------------
    6163
     
    7274        };
    7375    }
     76}
    7477
     78//-----------------------------------------------------------------------
     79// Forward declarations
     80//-----------------------------------------------------------------------
     81
     82namespace orxonox
     83{
    7584    class BillboardSet;
    7685    class Mesh;
    7786    class ParticleInterface;
     87    class ResourceCollection;
     88    class ResourceLocation;
    7889    class Shader;
    79     template <class T>
     90    class Tickable;
     91    class TimeFactorListener;
    8092    class Timer;
    81     class StaticTimer;
    8293}
    8394
  • code/trunk/src/libraries/util/CMakeLists.txt

    r5781 r5929  
    1919
    2020SET_SOURCE_FILES(UTIL_SRC_FILES
    21   Clipboard.cc
    22   CRC32.cc
    2321  Exception.cc
    24   ExprParser.cc
    2522  Math.cc
    2623  MultiType.cc
     24  Scope.cc
     25  StringUtils.cc
     26COMPILATION_BEGIN StableCompilation.cc
     27  Clipboard.cc
     28  Clock.cc
     29  CRC32.cc
     30  ExprParser.cc
    2731  OutputBuffer.cc
    2832  OutputHandler.cc
    29   Scope.cc
    3033  SignalHandler.cc
    3134  Sleep.cc
    32   StringUtils.cc
    3335  SubString.cc
     36COMPILATION_END
    3437)
    3538
  • code/trunk/src/libraries/util/Scope.h

    r5738 r5929  
    3131
    3232#include "UtilPrereqs.h"
     33
    3334#include <cassert>
     35#include <map>
    3436#include <set>
    35 #include <map>
     37
    3638#include "Debug.h"
     39#include "ScopeGuard.h"
    3740
    3841namespace orxonox
    3942{
    40     namespace ScopeID
    41     {
    42         /**
    43             @brief A list of available scopes for the Scope template.
    44         */
    45         enum Value
    46         {
    47             GSRoot,
    48             GSGraphics,
    49             GSLevel
    50         };
    51     }
    52 
    53     class ScopeListener; // Forward declaration
    54 
    5543    /**
    5644        @brief The ScopeManager stores the variables of the scope templates in a statically linked context.
     
    7765        protected:
    7866            //! Constructor: Registers the instance.
    79             ScopeListener(ScopeID::Value scope) : scope_(scope)
     67            ScopeListener(ScopeID::Value scope) : scope_(scope), bActivated_(false)
    8068                { ScopeManager::listeners_s[this->scope_].insert(this); }
    8169            //! Destructor: Unregisters the instance.
     
    9078        private:
    9179            ScopeID::Value scope_; //!< Store the scope to unregister on destruction
     80            bool bActivated_;
    9281    };
    9382
     
    10594            Scope()
    10695            {
    107                 ScopeManager::instanceCounts_s[scope]++;
    108                 assert(ScopeManager::instanceCounts_s[scope] > 0);
    109                 if (ScopeManager::instanceCounts_s[scope] == 1)
     96                try
    11097                {
    111                     for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
    112                         (*(it++))->activated();
     98                    ScopeManager::instanceCounts_s[scope]++;
     99                    assert(ScopeManager::instanceCounts_s[scope] > 0);
     100                    if (ScopeManager::instanceCounts_s[scope] == 1)
     101                    {
     102                        Loki::ScopeGuard deactivator = Loki::MakeObjGuard(*this, &Scope::deactivateListeners);
     103                        for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
     104                        {
     105                            (*it)->activated();
     106                            (*(it++))->bActivated_ = true;
     107                        }
     108                        deactivator.Dismiss();
     109                    }
     110                }
     111                catch (...)
     112                {
     113                    ScopeManager::instanceCounts_s[scope]--;
     114                    throw;
    113115                }
    114116            }
     
    125127
    126128                if (ScopeManager::instanceCounts_s[scope] == 0)
     129                    this->deactivateListeners();
     130            }
     131
     132            void deactivateListeners()
     133            {
     134                for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
    127135                {
    128                     for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
    129                         (*(it++))->deactivated();
     136                    if ((*it)->bActivated_)
     137                    {
     138                        try
     139                            { (*it)->deactivated(); }
     140                        catch (...)
     141                            { COUT(0) << "ScopeListener::deactivated() failed! This MUST NOT happen, fix it!" << std::endl; }
     142                        (*(it++))->bActivated_ = false;
     143                    }
     144                    else
     145                        ++it;
    130146                }
    131147            }
  • code/trunk/src/libraries/util/Singleton.h

    r5738 r5929  
    5555        }
    5656
     57        //! Update method called by ClassSingletonManager (if used)
     58        void updateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->update(time); }
     59        //! Empty update method for the static polymorphism
     60        void update(const Clock& time) { }
     61
    5762    protected:
    5863        //! Constructor sets the singleton instance pointer
  • code/trunk/src/libraries/util/UtilPrereqs.h

    r5738 r5929  
    2828
    2929/**
    30   @file
    31   @brief Contains all the necessary forward declarations for all classes and structs.
     30@file
     31@brief
     32    Shared library macros, enums, constants and forward declarations for the util library
    3233*/
    3334
     
    4041// Shared library settings
    4142//-----------------------------------------------------------------------
     43
    4244#if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( UTIL_STATIC_BUILD )
    4345#  ifdef UTIL_SHARED_BUILD
     
    5658#endif
    5759
     60//-----------------------------------------------------------------------
     61// Enums
     62//-----------------------------------------------------------------------
     63
     64namespace orxonox
     65{
     66    namespace ScopeID
     67    {
     68        //!A list of available scopes for the Scope template.
     69        enum Value
     70        {
     71            Root,
     72            Graphics
     73        };
     74    }
     75}
    5876
    5977//-----------------------------------------------------------------------
     
    6381namespace orxonox
    6482{
     83    class Clock;
    6584    class Exception;
    6685    class ExprParser;
     
    7190    class OutputBufferListener;
    7291    class OutputHandler;
     92    template <ScopeID::Value>
     93    class Scope;
     94    template <class, ScopeID::Value>
     95    class ScopedSingleton;
     96    class ScopeListener;
    7397    class SignalHandler;
     98    template <class T>
     99    class Singleton;
    74100    class SubString;
    75101}
Note: See TracChangeset for help on using the changeset viewer.