Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/BaseObject.cc @ 10328

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

merged core6 back to trunk

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