Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation2/src/libraries/core/BaseObject.cc @ 6735

Last change on this file since 6735 was 6400, checked in by rgrieder, 15 years ago

Replaced (*it). with it→ where I could find it. Should increased code readability.

  • Property svn:eol-style set to native
File size: 16.1 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30    @file
31    @brief Implementation of the BaseObject class.
32*/
33
34#include "BaseObject.h"
35
36#include <tinyxml/tinyxml.h>
37
38#include "CoreIncludes.h"
39#include "Event.h"
40#include "EventIncludes.h"
41#include "Functor.h"
42#include "Iterator.h"
43#include "Template.h"
44#include "XMLFile.h"
45#include "XMLNameListener.h"
46#include "XMLPort.h"
47
48namespace orxonox
49{
50    CreateFactory(BaseObject);
51
52    /**
53        @brief Constructor: Registers the object in the BaseObject-list.
54    */
55    BaseObject::BaseObject(BaseObject* creator) : bInitialized_(false)
56    {
57        RegisterRootObject(BaseObject);
58
59        this->bInitialized_ = true;
60
61        this->bActive_ = true;
62        this->bVisible_ = true;
63        this->oldGametype_ = 0;
64        this->bRegisteredEventStates_ = false;
65
66        this->lastLoadedXMLElement_ = 0;
67
68        this->mainStateFunctor_ = 0;
69
70        this->setCreator(creator);
71        if (this->creator_)
72        {
73            this->setFile(this->creator_->getFile());
74            this->setNamespace(this->creator_->getNamespace());
75            this->setScene(this->creator_->getScene(), this->creator_->getSceneID());
76            this->setGametype(this->creator_->getGametype());
77        }
78        else
79        {
80            this->file_ = 0;
81            this->namespace_ = 0;
82            this->scene_ = 0;
83            this->sceneID_ = OBJECTID_UNKNOWN;
84            this->gametype_ = 0;
85        }
86    }
87
88    /**
89        @brief Destructor
90    */
91    BaseObject::~BaseObject()
92    {
93        if (this->isInitialized())
94        {
95            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); )
96                this->removeEventSource((it++)->first);
97
98            for (std::set<BaseObject*>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); )
99                (*(it++))->removeEventSource(this);
100
101            for (std::map<std::string, EventState*>::const_iterator it = this->eventStates_.begin(); it != this->eventStates_.end(); ++it)
102                delete it->second;
103        }
104    }
105
106    /**
107        @brief XML loading and saving.
108        @param xmlelement The XML-element
109        @param loading Loading (true) or saving (false)
110    */
111    void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
112    {
113        XMLPortParam(BaseObject, "name", setXMLName, getName, xmlelement, mode);
114        XMLPortParam(BaseObject, "visible", setVisible, isVisible, xmlelement, mode);
115        XMLPortParam(BaseObject, "active", setActive, isActive, xmlelement, mode);
116        XMLPortParam(BaseObject, "mainstate", setMainStateName, getMainStateName, xmlelement, mode);
117
118        XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
119        XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode);
120
121        Element* events = 0;
122        if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
123            events = xmlelement.FirstChildElement("events", false);
124        else if (mode == XMLPort::SaveObject)
125            {}
126        if (events)
127            this->XMLEventPort(*events, mode);
128    }
129
130    /**
131        @brief Defines the possible event states of this object and parses eventsources from an XML file.
132        @param xmlelement The XML-element
133        @param loading Loading (true) or saving (false)
134    */
135    void BaseObject::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
136    {
137        XMLPortEventState(BaseObject, BaseObject, "activity", setActive, xmlelement, mode);
138        XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode);
139        XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode);
140
141        this->bRegisteredEventStates_ = true;
142    }
143
144    /**
145        @brief Loads the name of the object through XML and calls all XMLNameListener.
146        @param name The name of the object
147    */
148    void BaseObject::setXMLName(const std::string& name)
149    {
150        this->setName(name);
151
152        for (ObjectList<XMLNameListener>::iterator it = ObjectList<XMLNameListener>::begin(); it != ObjectList<XMLNameListener>::end(); ++it)
153            it->loadedNewXMLName(this);
154    }
155
156    /**
157        @brief Returns the levelfile that loaded this object.
158        @return The levelfile
159    */
160    const std::string& BaseObject::getFilename() const
161    {
162        if (this->file_)
163            return this->file_->getFilename();
164        else
165            return BLANKSTRING;
166    }
167
168    /**
169        @brief Adds a Template to the object.
170        @param name The name of the Template
171    */
172    void BaseObject::addTemplate(const std::string& name)
173    {
174        Template* temp = Template::getTemplate(name);
175        if (temp)
176            this->addTemplate(temp);
177        else
178            COUT(1) << "Error: \"" << name << "\" is not a valid Template name (in class: " << this->getIdentifier()->getName() << ", name: " << this->getName() << ")." << std::endl;
179    }
180
181    /**
182        @brief Adds a Template to the object.
183        @param temp The Template
184    */
185    void BaseObject::addTemplate(Template* temp)
186    {
187        this->templates_.insert(temp);
188        temp->applyOn(this);
189    }
190
191    /**
192        @brief Returns the Template with the given index.
193        @param index The index
194    */
195    Template* BaseObject::getTemplate(unsigned int index) const
196    {
197        unsigned int i = 0;
198        for (std::set<Template*>::const_iterator it = this->templates_.begin(); it != this->templates_.end(); ++it)
199        {
200            if (i == index)
201                return (*it);
202            i++;
203        }
204        return 0;
205    }
206
207    /**
208        @brief Adds a new event source for a specific state.
209        @param source The object which sends events to this object
210        @param state The state of this object which will be affected by the events
211    */
212    void BaseObject::addEventSource(BaseObject* source, const std::string& state)
213    {
214        this->eventSources_[source] = state;
215        source->registerEventListener(this);
216    }
217
218    /**
219        @brief Removes an eventsource (but doesn't unregister itself at the source).
220    */
221    void BaseObject::removeEventSource(BaseObject* source)
222    {
223        this->eventSources_.erase(source);
224        source->unregisterEventListener(this);
225    }
226
227    /**
228        @brief Returns an eventsource with a given index.
229    */
230    BaseObject* BaseObject::getEventSource(unsigned int index, const std::string& state) const
231    {
232        unsigned int i = 0;
233        for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); ++it)
234        {
235            if (it->second != state)
236                continue;
237
238            if (i == index)
239                return it->first;
240            ++i;
241        }
242        return 0;
243    }
244
245    /**
246        @brief Adds an object which listens to the events of this object. The events are sent to the other objects mainstate.
247    */
248    void BaseObject::addEventListener(BaseObject* listener)
249    {
250        this->eventListenersXML_.insert(listener);
251        listener->addEventSource(this, "mainstate");
252    }
253
254    /**
255        @brief Returns an event listener with a given index.
256    */
257    BaseObject* BaseObject::getEventListener(unsigned int index) const
258    {
259        unsigned int i = 0;
260        for (std::set<BaseObject*>::const_iterator it = this->eventListenersXML_.begin(); it != this->eventListenersXML_.end(); ++it)
261        {
262            if (i == index)
263                return *it;
264            ++i;
265        }
266        return 0;
267    }
268
269    /**
270        @brief Adds a new event-state to the object. Event-states are states which can be changed by events.
271        @param name  The name of the event
272        @param state The object containing information about the event-state
273    */
274    void BaseObject::addEventState(const std::string& name, EventState* state)
275    {
276        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
277        if (it != this->eventStates_.end())
278        {
279            COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << '.' << std::endl;
280            delete (it->second);
281        }
282
283        this->eventStates_[name] = state;
284    }
285
286    /**
287        @brief Returns the event-state with the given name.
288    */
289    EventState* BaseObject::getEventState(const std::string& name) const
290    {
291        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
292        if (it != this->eventStates_.end())
293            return (it->second);
294        else
295            return 0;
296    }
297
298    /**
299        @brief Fires an event (without a state).
300    */
301    void BaseObject::fireEvent(const std::string& name)
302    {
303        this->fireEvent(true, name);
304        this->fireEvent(false, name);
305    }
306
307    /**
308        @brief Fires an event which activates or deactivates a state.
309    */
310    void BaseObject::fireEvent(bool activate, const std::string& name)
311    {
312        this->fireEvent(activate, this, name);
313    }
314
315    /**
316        @brief Fires an event which activates or deactivates a state with agiven originator (the object which triggered the event).
317    */
318    void BaseObject::fireEvent(bool activate, BaseObject* originator, const std::string& name)
319    {
320        Event event(activate, originator, name);
321
322        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
323        {
324            event.statename_ = (*it)->eventSources_[this];
325            (*it)->processEvent(event);
326        }
327    }
328
329    /**
330        @brief Fires an event, using the Event struct.
331    */
332    void BaseObject::fireEvent(Event& event)
333    {
334        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
335            (*it)->processEvent(event);
336    }
337
338    /**
339        @brief Processing an event by calling the right main state.
340        @param event The event struct which contains the information about the event
341    */
342    void BaseObject::processEvent(Event& event)
343    {
344        this->registerEventStates();
345
346        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_);
347        if (it != this->eventStates_.end())
348            it->second->process(event, this);
349        else if (!event.statename_.empty())
350            COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
351        else
352            COUT(2) << "Warning: Event with invalid source sent to object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
353    }
354
355    /**
356        @brief Sets the main state of the object to a given boolean value.
357
358        Note: The main state of an object can be set with the @ref setMainStateName function.
359        It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state,
360        the main state is used by default).
361    */
362    void BaseObject::setMainState(bool state)
363    {
364        if (this->mainStateFunctor_)
365        {
366            if (this->mainStateFunctor_->getParamCount() == 0)
367            {
368                if (state)
369                    (*this->mainStateFunctor_)();
370            }
371            else
372            {
373                (*this->mainStateFunctor_)(state);
374            }
375        }
376        else
377            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
378    }
379
380    /**
381        @brief This function gets called if the main state name of the object changes.
382    */
383    void BaseObject::changedMainStateName()
384    {
385        this->mainStateFunctor_ = 0;
386
387        if (!this->mainStateName_.empty())
388        {
389            this->registerEventStates();
390
391            std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_);
392            if (it != this->eventStates_.end() && it->second->getFunctor())
393            {
394                if (it->second->getFunctor()->getParamCount() <= 1)
395                    this->mainStateFunctor_ = it->second->getFunctor();
396                else
397                    COUT(2) << "Warning: Can't use \"" << this->mainStateName_ << "\" as MainState because it needs a second argument." << std::endl;
398            }
399            else
400                COUT(2) << "Warning: \"" << this->mainStateName_ << "\" is not a valid MainState." << std::endl;
401        }
402    }
403
404    /**
405        @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary.
406    */
407    void BaseObject::registerEventStates()
408    {
409        if (!this->bRegisteredEventStates_)
410        {
411            Element xmlelement;
412            this->XMLEventPort(xmlelement, XMLPort::NOP);
413        }
414    }
415
416    /**
417        @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.
418    */
419    void BaseObject::loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier)
420    {
421        Element* events = xmlelement.FirstChildElement("events", false);
422        if (events)
423        {
424            // get the list of all states present
425            std::list<std::string> eventnames;
426            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
427            {
428                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
429                    eventnames.push_back(child->Value());
430            }
431            else if (mode == XMLPort::SaveObject)
432            {
433            }
434
435            // iterate through all states and get the event sources
436            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
437            {
438                const std::string& statename = (*it);
439
440                // if the event state is already known, continue with the next state
441                orxonox::EventState* eventstate = object->getEventState(statename);
442                if (eventstate)
443                    continue;
444
445                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(identifier->getXMLPortObjectContainer(statename));
446                if (!container)
447                {
448                    ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + '(' + statename + ')');
449                    ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + '(' + statename + ')');
450                    setfunctor->setDefaultValue(1, statename);
451                    getfunctor->setDefaultValue(1, statename);
452
453                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(statename, identifier, setfunctor, getfunctor, false, true);
454                    identifier->addXMLPortObjectContainer(statename, container);
455                }
456                container->port(object, *events, mode);
457            }
458        }
459    }
460}
Note: See TracBrowser for help on using the repository browser.