Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/lod/src/libraries/core/BaseObject.cc @ 6829

Last change on this file since 6829 was 6829, checked in by scheusso, 14 years ago

no tabs ;)

  • Property svn:eol-style set to native
File size: 16.6 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            this->setLevel(this->creator_->getLevel());
78        }
79        else
80        {
81            this->file_ = 0;
82            this->namespace_ = 0;
83            this->scene_ = 0;
84            this->sceneID_ = OBJECTID_UNKNOWN;
85            this->gametype_ = 0;
86            this->level_ = 0;
87        }
88    }
89
90    /**
91        @brief Destructor
92    */
93    BaseObject::~BaseObject()
94    {
95        if (this->isInitialized())
96        {
97            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); )
98                this->removeEventSource((it++)->first);
99
100            for (std::set<BaseObject*>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); )
101                (*(it++))->removeEventSource(this);
102
103            for (std::map<std::string, EventState*>::const_iterator it = this->eventStates_.begin(); it != this->eventStates_.end(); ++it)
104                delete it->second;
105        }
106    }
107
108    /**
109        @brief XML loading and saving.
110        @param xmlelement The XML-element
111        @param loading Loading (true) or saving (false)
112    */
113    void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
114    {
115        XMLPortParam(BaseObject, "name", setXMLName, getName, xmlelement, mode);
116        XMLPortParam(BaseObject, "visible", setVisible, isVisible, xmlelement, mode);
117        XMLPortParam(BaseObject, "active", setActive, isActive, xmlelement, mode);
118        XMLPortParam(BaseObject, "mainstate", setMainStateName, getMainStateName, xmlelement, mode);
119        XMLPortParamTemplate(BaseObject, "template", addTemplate, getSingleTemplate, xmlelement, mode, const std::string&);
120       
121        XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
122        XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode);
123
124        Element* events = 0;
125        if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
126            events = xmlelement.FirstChildElement("events", false);
127        else if (mode == XMLPort::SaveObject)
128            {}
129        if (events)
130            this->XMLEventPort(*events, mode);
131    }
132
133    /**
134        @brief Defines the possible event states of this object and parses eventsources from an XML file.
135        @param xmlelement The XML-element
136        @param loading Loading (true) or saving (false)
137    */
138    void BaseObject::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
139    {
140        XMLPortEventState(BaseObject, BaseObject, "activity", setActive, xmlelement, mode);
141        XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode);
142        XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode);
143
144        this->bRegisteredEventStates_ = true;
145    }
146
147    /**
148        @brief Loads the name of the object through XML and calls all XMLNameListener.
149        @param name The name of the object
150    */
151    void BaseObject::setXMLName(const std::string& name)
152    {
153        this->setName(name);
154
155        for (ObjectList<XMLNameListener>::iterator it = ObjectList<XMLNameListener>::begin(); it != ObjectList<XMLNameListener>::end(); ++it)
156            it->loadedNewXMLName(this);
157    }
158
159    /**
160        @brief Returns the levelfile that loaded this object.
161        @return The levelfile
162    */
163    const std::string& BaseObject::getFilename() const
164    {
165        if (this->file_)
166            return this->file_->getFilename();
167        else
168            return BLANKSTRING;
169    }
170
171    /**
172        @brief Adds a Template to the object.
173        @param name The name of the Template
174    */
175    void BaseObject::addTemplate(const std::string& name)
176    {
177        Template* temp = Template::getTemplate(name);
178        if (temp)
179            this->addTemplate(temp);
180        else
181            COUT(1) << "Error: \"" << name << "\" is not a valid Template name (in class: " << this->getIdentifier()->getName() << ", name: " << this->getName() << ")." << std::endl;
182    }
183
184    /**
185        @brief Adds a Template to the object.
186        @param temp The Template
187    */
188    void BaseObject::addTemplate(Template* temp)
189    {
190        this->templates_.insert(temp);
191        temp->applyOn(this);
192    }
193
194    /**
195        @brief Returns the name of the first Template.
196        @return The name as string.
197    */
198    const std::string& BaseObject::getSingleTemplate(void) const
199    {
200        if(this->templates_.empty())
201            return BLANKSTRING;
202
203        return (*this->templates_.begin())->getName();
204    }
205
206    /**
207        @brief Returns the Template with the given index.
208        @param index The index
209    */
210    Template* BaseObject::getTemplate(unsigned int index) const
211    {
212        unsigned int i = 0;
213        for (std::set<Template*>::const_iterator it = this->templates_.begin(); it != this->templates_.end(); ++it)
214        {
215            if (i == index)
216                return (*it);
217            i++;
218        }
219        return 0;
220    }
221
222    /**
223        @brief Adds a new event source for a specific state.
224        @param source The object which sends events to this object
225        @param state The state of this object which will be affected by the events
226    */
227    void BaseObject::addEventSource(BaseObject* source, const std::string& state)
228    {
229        this->eventSources_[source] = state;
230        source->registerEventListener(this);
231    }
232
233    /**
234        @brief Removes an eventsource (but doesn't unregister itself at the source).
235    */
236    void BaseObject::removeEventSource(BaseObject* source)
237    {
238        this->eventSources_.erase(source);
239        source->unregisterEventListener(this);
240    }
241
242    /**
243        @brief Returns an eventsource with a given index.
244    */
245    BaseObject* BaseObject::getEventSource(unsigned int index, const std::string& state) const
246    {
247        unsigned int i = 0;
248        for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); ++it)
249        {
250            if (it->second != state)
251                continue;
252
253            if (i == index)
254                return it->first;
255            ++i;
256        }
257        return 0;
258    }
259
260    /**
261        @brief Adds an object which listens to the events of this object. The events are sent to the other objects mainstate.
262    */
263    void BaseObject::addEventListener(BaseObject* listener)
264    {
265        this->eventListenersXML_.insert(listener);
266        listener->addEventSource(this, "mainstate");
267    }
268
269    /**
270        @brief Returns an event listener with a given index.
271    */
272    BaseObject* BaseObject::getEventListener(unsigned int index) const
273    {
274        unsigned int i = 0;
275        for (std::set<BaseObject*>::const_iterator it = this->eventListenersXML_.begin(); it != this->eventListenersXML_.end(); ++it)
276        {
277            if (i == index)
278                return *it;
279            ++i;
280        }
281        return 0;
282    }
283
284    /**
285        @brief Adds a new event-state to the object. Event-states are states which can be changed by events.
286        @param name  The name of the event
287        @param state The object containing information about the event-state
288    */
289    void BaseObject::addEventState(const std::string& name, EventState* state)
290    {
291        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
292        if (it != this->eventStates_.end())
293        {
294            COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << '.' << std::endl;
295            delete (it->second);
296        }
297
298        this->eventStates_[name] = state;
299    }
300
301    /**
302        @brief Returns the event-state with the given name.
303    */
304    EventState* BaseObject::getEventState(const std::string& name) const
305    {
306        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
307        if (it != this->eventStates_.end())
308            return (it->second);
309        else
310            return 0;
311    }
312
313    /**
314        @brief Fires an event (without a state).
315    */
316    void BaseObject::fireEvent(const std::string& name)
317    {
318        this->fireEvent(true, name);
319        this->fireEvent(false, name);
320    }
321
322    /**
323        @brief Fires an event which activates or deactivates a state.
324    */
325    void BaseObject::fireEvent(bool activate, const std::string& name)
326    {
327        this->fireEvent(activate, this, name);
328    }
329
330    /**
331        @brief Fires an event which activates or deactivates a state with agiven originator (the object which triggered the event).
332    */
333    void BaseObject::fireEvent(bool activate, BaseObject* originator, const std::string& name)
334    {
335        Event event(activate, originator, name);
336
337        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
338        {
339            event.statename_ = (*it)->eventSources_[this];
340            (*it)->processEvent(event);
341        }
342    }
343
344    /**
345        @brief Fires an event, using the Event struct.
346    */
347    void BaseObject::fireEvent(Event& event)
348    {
349        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
350            (*it)->processEvent(event);
351    }
352
353    /**
354        @brief Processing an event by calling the right main state.
355        @param event The event struct which contains the information about the event
356    */
357    void BaseObject::processEvent(Event& event)
358    {
359        this->registerEventStates();
360
361        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_);
362        if (it != this->eventStates_.end())
363            it->second->process(event, this);
364        else if (!event.statename_.empty())
365            COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
366        else
367            COUT(2) << "Warning: Event with invalid source sent to object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
368    }
369
370    /**
371        @brief Sets the main state of the object to a given boolean value.
372
373        Note: The main state of an object can be set with the @ref setMainStateName function.
374        It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state,
375        the main state is used by default).
376    */
377    void BaseObject::setMainState(bool state)
378    {
379        if (this->mainStateFunctor_)
380        {
381            if (this->mainStateFunctor_->getParamCount() == 0)
382            {
383                if (state)
384                    (*this->mainStateFunctor_)();
385            }
386            else
387            {
388                (*this->mainStateFunctor_)(state);
389            }
390        }
391        else
392            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
393    }
394
395    /**
396        @brief This function gets called if the main state name of the object changes.
397    */
398    void BaseObject::changedMainStateName()
399    {
400        this->mainStateFunctor_ = 0;
401
402        if (!this->mainStateName_.empty())
403        {
404            this->registerEventStates();
405
406            std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_);
407            if (it != this->eventStates_.end() && it->second->getFunctor())
408            {
409                if (it->second->getFunctor()->getParamCount() <= 1)
410                    this->mainStateFunctor_ = it->second->getFunctor();
411                else
412                    COUT(2) << "Warning: Can't use \"" << this->mainStateName_ << "\" as MainState because it needs a second argument." << std::endl;
413            }
414            else
415                COUT(2) << "Warning: \"" << this->mainStateName_ << "\" is not a valid MainState." << std::endl;
416        }
417    }
418
419    /**
420        @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary.
421    */
422    void BaseObject::registerEventStates()
423    {
424        if (!this->bRegisteredEventStates_)
425        {
426            Element xmlelement;
427            this->XMLEventPort(xmlelement, XMLPort::NOP);
428        }
429    }
430
431    /**
432        @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.
433    */
434    void BaseObject::loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier)
435    {
436        Element* events = xmlelement.FirstChildElement("events", false);
437        if (events)
438        {
439            // get the list of all states present
440            std::list<std::string> eventnames;
441            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
442            {
443                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
444                    eventnames.push_back(child->Value());
445            }
446            else if (mode == XMLPort::SaveObject)
447            {
448            }
449
450            // iterate through all states and get the event sources
451            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
452            {
453                const std::string& statename = (*it);
454
455                // if the event state is already known, continue with the next state
456                orxonox::EventState* eventstate = object->getEventState(statename);
457                if (eventstate)
458                    continue;
459
460                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(identifier->getXMLPortObjectContainer(statename));
461                if (!container)
462                {
463                    ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + '(' + statename + ')');
464                    ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + '(' + statename + ')');
465                    setfunctor->setDefaultValue(1, statename);
466                    getfunctor->setDefaultValue(1, statename);
467
468                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(statename, identifier, setfunctor, getfunctor, false, true);
469                    identifier->addXMLPortObjectContainer(statename, container);
470                }
471                container->port(object, *events, mode);
472            }
473        }
474    }
475}
Note: See TracBrowser for help on using the repository browser.