Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Ignore:
Timestamp:
Feb 14, 2009, 10:17:35 PM (16 years ago)
Author:
rgrieder
Message:

Merged presentation branch back to trunk.

Location:
code/trunk
Files:
2 deleted
126 edited
59 copied

Legend:

Unmodified
Added
Removed
  • code/trunk

  • code/trunk/src/orxonox/objects/CMakeLists.txt

    r2171 r2662  
    33  EventDispatcher.cc
    44  EventTarget.cc
     5  GlobalShader.cc
    56  Level.cc
    67  Radar.cc
     
    1314)
    1415
     16ADD_SOURCE_DIRECTORY(SRC_FILES collisionshapes)
    1517ADD_SOURCE_DIRECTORY(SRC_FILES controllers)
    1618ADD_SOURCE_DIRECTORY(SRC_FILES gametypes)
    1719ADD_SOURCE_DIRECTORY(SRC_FILES infos)
    18 #ADD_SOURCE_DIRECTORY(SRC_FILES pickup)
     20ADD_SOURCE_DIRECTORY(SRC_FILES items)
     21ADD_SOURCE_DIRECTORY(SRC_FILES pickup)
    1922ADD_SOURCE_DIRECTORY(SRC_FILES quest)
    2023ADD_SOURCE_DIRECTORY(SRC_FILES weaponSystem)
  • code/trunk/src/orxonox/objects/EventTarget.cc

    r2087 r2662  
    4848    void EventTarget::changedName()
    4949    {
     50        SUPER(EventTarget, changedName);
     51
    5052        for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); ++it)
    5153            if (it->getName() == this->getName())
  • code/trunk/src/orxonox/objects/Level.cc

    r2261 r2662  
    8383    void Level::registerVariables()
    8484    {
    85         REGISTERSTRING(this->xmlfilename_, direction::toclient, new NetworkCallback<Level>(this, &Level::networkcallback_applyXMLFile));
    86         REGISTERSTRING(this->name_,        direction::toclient, new NetworkCallback<Level>(this, &Level::changedName));
    87         REGISTERSTRING(this->description_, direction::toclient);
     85        registerVariable(this->xmlfilename_, variableDirection::toclient, new NetworkCallback<Level>(this, &Level::networkcallback_applyXMLFile));
     86        registerVariable(this->name_,        variableDirection::toclient, new NetworkCallback<Level>(this, &Level::changedName));
     87        registerVariable(this->description_, variableDirection::toclient);
    8888    }
    8989
     
    141141    void Level::playerEntered(PlayerInfo* player)
    142142    {
    143         COUT(3) << "player entered level" << std::endl;
     143        COUT(3) << "player entered level (id: " << player->getClientID() << ", name: " << player->getName() << ")" << std::endl;
    144144        player->setGametype(this->getGametype());
    145145    }
     
    147147    void Level::playerLeft(PlayerInfo* player)
    148148    {
    149         COUT(3) << "player left level" << std::endl;
     149        COUT(3) << "player left level (id: " << player->getClientID() << ", name: " << player->getName() << ")" << std::endl;
    150150        player->setGametype(0);
    151151    }
  • code/trunk/src/orxonox/objects/Level.h

    r2261 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333
    34 #include "network/Synchronisable.h"
     34#include "network/synchronisable/Synchronisable.h"
    3535#include "core/BaseObject.h"
    3636
  • code/trunk/src/orxonox/objects/Radar.cc

    r2087 r2662  
    9999    void Radar::tick(float dt)
    100100    {
     101        SUPER(Radar, tick, dt);
     102
    101103        if (this->focus_ != *(this->itFocus_))
    102104        {
     
    112114            for (ObjectList<RadarViewable>::iterator itElement = ObjectList<RadarViewable>::begin(); itElement; ++itElement)
    113115            {
    114 /*
    115                 if ((*itElement) != SpaceShip::getLocalShip() && (*itListener)->getRadarSensitivity() > (*itElement)->getRadarObjectCamouflage())
     116                if ((*itListener)->getRadarSensitivity() > (*itElement)->getRadarObjectCamouflage())
    116117                    (*itListener)->displayObject(*itElement, *itElement == this->focus_);
    117 */
    118118            }
    119119        }
     
    128128            this->focus_ = 0;
    129129        }
    130         else
    131         {
    132             Vector3 localPosition;// = SpaceShip::getLocalShip()->getPosition();
     130/*
     131        else if (this->owner_)
     132        {
     133            Vector3 localPosition = this->owner_->getPosition();
    133134            Vector3 targetPosition = localPosition;
    134135            if (*(this->itFocus_))
    135                 targetPosition = this->itFocus_->getWorldPosition();
     136                targetPosition = this->itFocus_->getRVWorldPosition();
    136137
    137138            // find the closed object further away than targetPosition
     
    143144            for (ObjectList<RadarViewable>::iterator it = ObjectList<RadarViewable>::begin(); it; ++it)
    144145            {
    145 /*
    146                 if (*it == SpaceShip::getLocalShip())
     146                if (*it == (RadarViewable*)this->owner_)
    147147                    continue;
    148 */
    149                 float targetDistance = localPosition.squaredDistance((*it)->getWorldPosition());
     148
     149                float targetDistance = localPosition.squaredDistance((*it)->getRVWorldPosition());
    150150                if (targetDistance > currentDistance && targetDistance < nextDistance)
    151151                {
     
    171171            }
    172172        }
     173*/
    173174    }
    174175
     
    186187        for (ObjectList<RadarViewable>::iterator it = ObjectList<RadarViewable>::begin(); it; ++it, ++i)
    187188        {
    188             COUT(3) << i++ << ": " << (*it)->getWorldPosition() << std::endl;
     189            COUT(3) << i++ << ": " << (*it)->getRVWorldPosition() << std::endl;
    189190        }
    190191    }
  • code/trunk/src/orxonox/objects/RadarViewable.cc

    r2087 r2662  
    2929#include "OrxonoxStableHeaders.h"
    3030#include "RadarViewable.h"
     31
    3132#include "util/Debug.h"
     33#include "util/Exception.h"
    3234#include "core/CoreIncludes.h"
    33 //#include "objects/WorldEntity.h"
    34 #include "Radar.h"
     35#include "objects/worldentities/WorldEntity.h"
     36#include "objects/Radar.h"
    3537
    3638namespace orxonox
     
    4042    */
    4143    RadarViewable::RadarViewable()
    42         : radarObject_(0)
    43         , radarObjectCamouflage_(0.0f)
    44         , radarObjectType_(Dot)
     44        : radarObjectCamouflage_(0.0f)
     45        , radarObjectShape_(Dot)
    4546        , radarObjectDescription_("staticObject")
    4647    {
     
    5253        Radar* radar = Radar::getInstancePtr();
    5354        if (radar)
    54             this->radarObjectType_ = radar->addObjectDescription(str);
     55            this->radarObjectShape_ = radar->addObjectDescription(str);
    5556        else
    5657        {
     
    6061    }
    6162
    62     const Vector3& RadarViewable::getWorldPosition() const
     63    const Vector3& RadarViewable::getRVWorldPosition() const
    6364    {
    64         validate();
    65         return Vector3::ZERO;//this->radarObject_->getWorldPosition();
     65        const WorldEntity* object = this->getWorldEntity();
     66        validate(object);
     67        return object->getWorldPosition();
    6668    }
    6769
    68     Vector3 RadarViewable::getOrientedVelocity() const
     70    Vector3 RadarViewable::getRVOrientedVelocity() const
    6971    {
    70         validate();
    71         return Vector3::ZERO;//this->radarObject_->getOrientation() * this->radarObject_->getVelocity();
     72        const WorldEntity* object = this->getWorldEntity();
     73        validate(object);
     74        return object->getWorldOrientation() * object->getVelocity();
    7275    }
    7376}
  • code/trunk/src/orxonox/objects/RadarViewable.h

    r2087 r2662  
    4444    class _OrxonoxExport RadarViewable : virtual public OrxonoxClass
    4545    {
    46     class WorldEntity;
    47 
    4846    public:
    4947        enum Shape
     
    5856        virtual ~RadarViewable() { }
    5957
    60         float getRadarObjectCamouflage() const { return this->radarObjectCamouflage_; }
    61         void setRadarObjectCamouflage(float camouflage) { this->radarObjectCamouflage_ = camouflage; }
     58        inline void setRadarObjectCamouflage(float camouflage)
     59            { this->radarObjectCamouflage_ = camouflage; }
     60        inline float getRadarObjectCamouflage() const
     61            { return this->radarObjectCamouflage_; }
    6262
    63         const ColourValue& getRadarObjectColour() const { return this->radarObjectColour_; }
    64         void setRadarObjectColour(const ColourValue& colour) { this->radarObjectColour_ = colour; }
     63        inline void setRadarObjectColour(const ColourValue& colour)
     64            { this->radarObjectColour_ = colour; }
     65        inline const ColourValue& getRadarObjectColour() const
     66            { return this->radarObjectColour_; }
    6567
    66         const std::string& getRadarObjectDescription() const { return this->radarObjectDescription_; }
    6768        void setRadarObjectDescription(const std::string& str);
     69        inline const std::string& getRadarObjectDescription() const
     70            { return this->radarObjectDescription_; }
    6871
    69         const WorldEntity* getWorldEntity() const { return this->radarObject_; }
    70         const Vector3& getWorldPosition() const;
    71         Vector3 getOrientedVelocity() const;
     72        virtual const WorldEntity* getWorldEntity() const = 0;
    7273
    73         Shape getRadarObjectType() const { return this->radarObjectType_; }
     74        const Vector3& getRVWorldPosition() const;
     75        Vector3 getRVOrientedVelocity() const;
    7476
    75     protected:
    76         WorldEntity* radarObject_;
     77        inline void setRadarObjectShape(Shape shape)
     78            { this->radarObjectShape_ = shape; }
     79        inline Shape getRadarObjectShape() const
     80            { return this->radarObjectShape_; }
    7781
    7882    private:
    79         void validate() const { if (!this->radarObject_)
    80         { COUT(1) << "Assertation: Every RadarViewable has to be assigned a WorldEntity pointer!" << std::endl; assert(0); } }
     83        void validate(const WorldEntity* object) const
     84        {
     85            if (!object)
     86            {
     87                COUT(1) << "Assertation: Every RadarViewable has to be assigned a WorldEntity pointer!" << std::endl;
     88                assert(0);
     89            }
     90        }
    8191
    8292        float radarObjectCamouflage_;
    83         Shape radarObjectType_;
     93        Shape radarObjectShape_;
    8494        std::string radarObjectDescription_;
    8595        ColourValue radarObjectColour_;
  • code/trunk/src/orxonox/objects/Scene.cc

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder (physics)
    2425 *   Co-authors:
    2526 *      ...
     
    3334#include <OgreSceneManagerEnumerator.h>
    3435#include <OgreSceneNode.h>
    35 #include <OgreLight.h>
     36
     37#include "BulletCollision/BroadphaseCollision/btAxisSweep3.h"
     38#include "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h"
     39#include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h"
     40#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
    3641
    3742#include "core/CoreIncludes.h"
    3843#include "core/Core.h"
    3944#include "core/XMLPort.h"
     45#include "tools/BulletConversions.h"
     46#include "objects/worldentities/WorldEntity.h"
    4047
    4148namespace orxonox
     
    4855
    4956        this->setScene(this);
    50         this->bShadows_ = false;
     57        this->bShadows_ = true;
    5158
    5259        if (Core::showsGraphics())
     
    7077        }
    7178
    72         // test test test
    73         if (Core::showsGraphics() && this->sceneManager_)
    74         {
    75             Ogre::Light* light;
    76             light = this->sceneManager_->createLight("Light-1");
    77             light->setType(Ogre::Light::LT_DIRECTIONAL);
    78             light->setDiffuseColour(ColourValue(1.0, 0.9, 0.6, 1.0));
    79             light->setSpecularColour(ColourValue(1.0, 0.9, 0.6, 1.0));
    80             light->setDirection(1, -0.3, 0.3);
    81         }
    82         // test test test
     79        // No physics yet, XMLPort will do that.
     80        const int defaultMaxWorldSize = 100000;
     81        this->negativeWorldRange_ = Vector3::UNIT_SCALE * -defaultMaxWorldSize;
     82        this->positiveWorldRange_ = Vector3::UNIT_SCALE *  defaultMaxWorldSize;
     83        this->gravity_ = Vector3::ZERO;
     84        this->physicalWorld_   = 0;
     85        this->solver_          = 0;
     86        this->dispatcher_      = 0;
     87        this->collisionConfig_ = 0;
     88        this->broadphase_      = 0;
    8389
    8490        this->registerVariables();
     
    9197            if (Ogre::Root::getSingletonPtr())
    9298            {
    93 //                this->sceneManager_->destroySceneNode(this->rootSceneNode_->getName()); // TODO: remove getName() for newer versions of Ogre
    9499                Ogre::Root::getSingleton().destroySceneManager(this->sceneManager_);
    95100            }
     
    98103                delete this->sceneManager_;
    99104            }
     105
     106            this->setPhysicalWorld(false);
    100107        }
    101108    }
     
    109116        XMLPortParam(Scene, "shadow", setShadow, getShadow, xmlelement, mode).defaultValues(true);
    110117
     118        XMLPortParam(Scene, "gravity", setGravity, getGravity, xmlelement, mode);
     119        XMLPortParam(Scene, "negativeWorldRange", setNegativeWorldRange, getNegativeWorldRange, xmlelement, mode);
     120        XMLPortParam(Scene, "positiveWorldRange", setPositiveWorldRange, getPositiveWorldRange, xmlelement, mode);
     121        XMLPortParam(Scene, "hasPhysics", setPhysicalWorld, hasPhysics, xmlelement, mode).defaultValues(true);
     122
    111123        XMLPortObjectExtended(Scene, BaseObject, "", addObject, getObject, xmlelement, mode, true, false);
    112124    }
     
    114126    void Scene::registerVariables()
    115127    {
    116         REGISTERSTRING(this->skybox_,     direction::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applySkybox));
    117         REGISTERDATA(this->ambientLight_, direction::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyAmbientLight));
     128        registerVariable(this->skybox_,             variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applySkybox));
     129        registerVariable(this->ambientLight_,       variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyAmbientLight));
     130        registerVariable(this->negativeWorldRange_, variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_negativeWorldRange));
     131        registerVariable(this->positiveWorldRange_, variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_positiveWorldRange));
     132        registerVariable(this->gravity_,            variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_gravity));
     133        registerVariable(this->bHasPhysics_,        variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_hasPhysics));
     134        registerVariable(this->bShadows_,           variableDirection::toclient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyShadows));
     135    }
     136
     137    void Scene::setNegativeWorldRange(const Vector3& range)
     138    {
     139        if (range.length() < 10.0f)
     140        {
     141            CCOUT(2) << "Warning: Setting the negative world range to a very small value: "
     142                     << omni_cast<std::string>(range) << std::endl;
     143        }
     144        if (this->hasPhysics())
     145        {
     146            CCOUT(2) << "Warning: Attempting to set the physical world range at run time. "
     147                     << "This causes a complete physical reload which might take some time." << std::endl;
     148            this->setPhysicalWorld(false);
     149            this->negativeWorldRange_ = range;
     150            this->setPhysicalWorld(true);
     151        }
     152        else
     153            this->negativeWorldRange_ = range;
     154    }
     155
     156    void Scene::setPositiveWorldRange(const Vector3& range)
     157    {
     158        if (range.length() < 10.0f)
     159        {
     160            CCOUT(2) << "Warning: Setting the positive world range to a very small value: "
     161                     << omni_cast<std::string>(range) << std::endl;
     162        }
     163        if (this->hasPhysics())
     164        {
     165            CCOUT(2) << "Warning: Attempting to set the physical world range at run time. "
     166                     << "This causes a complete physical reload which might take some time." << std::endl;
     167            this->setPhysicalWorld(false);
     168            this->positiveWorldRange_ = range;
     169            this->setPhysicalWorld(true);
     170        }
     171        else
     172            this->positiveWorldRange_ = range;
     173    }
     174
     175    void Scene::setGravity(const Vector3& gravity)
     176    {
     177        this->gravity_ = gravity;
     178        if (this->hasPhysics())
     179            this->physicalWorld_->setGravity(omni_cast<btVector3>(this->gravity_));
     180    }
     181
     182    void Scene::setPhysicalWorld(bool wantPhysics)
     183    {
     184        this->bHasPhysics_ = wantPhysics;
     185        if (wantPhysics && !hasPhysics())
     186        {
     187            // Note: These are all little known default classes and values.
     188            //       It would require further investigation to properly dertermine the right choices.
     189            this->broadphase_      = new bt32BitAxisSweep3(
     190                omni_cast<btVector3>(this->negativeWorldRange_), omni_cast<btVector3>(this->positiveWorldRange_));
     191            this->collisionConfig_ = new btDefaultCollisionConfiguration();
     192            this->dispatcher_      = new btCollisionDispatcher(this->collisionConfig_);
     193            this->solver_          = new btSequentialImpulseConstraintSolver();
     194
     195            this->physicalWorld_   = new btDiscreteDynamicsWorld(this->dispatcher_, this->broadphase_, this->solver_, this->collisionConfig_);
     196            this->physicalWorld_->setGravity(omni_cast<btVector3>(this->gravity_));
     197
     198            // also set the collision callback variable.
     199            // Note: This is a global variable which we assign a static function.
     200            // TODO: Check whether this (or anything about Bullet) works with multiple physics engine instances.
     201            gContactAddedCallback = &Scene::collisionCallback;
     202        }
     203        else if (!wantPhysics && hasPhysics())
     204        {
     205            // Remove all WorldEntities and shove them to the queue since they would still like to be in a physical world.
     206            for (std::set<WorldEntity*>::const_iterator it = this->physicalObjects_.begin();
     207                it != this->physicalObjects_.end(); ++it)
     208            {
     209                this->physicalWorld_->removeRigidBody((*it)->physicalBody_);
     210                this->physicalObjectQueue_.insert(*it);
     211            }
     212            this->physicalObjects_.clear();
     213
     214            delete this->physicalWorld_;
     215            delete this->solver_;
     216            delete this->dispatcher_;
     217            delete this->collisionConfig_;
     218            delete this->broadphase_;
     219            this->physicalWorld_   = 0;
     220            this->solver_          = 0;
     221            this->dispatcher_      = 0;
     222            this->collisionConfig_ = 0;
     223            this->broadphase_      = 0;
     224        }
     225    }
     226
     227    void Scene::tick(float dt)
     228    {
     229        if (!Core::showsGraphics())
     230        {
     231            // We need to update the scene nodes if we don't render
     232            this->rootSceneNode_->_update(true, false);
     233        }
     234        if (this->hasPhysics())
     235        {
     236            // TODO: This here is bad practice! It will slow down the first tick() by ages.
     237            //       Rather have an initialise() method as well, called by the Level after everything has been loaded.
     238            if (this->physicalObjectQueue_.size() > 0)
     239            {
     240                // Add all scheduled WorldEntities
     241                for (std::set<WorldEntity*>::const_iterator it = this->physicalObjectQueue_.begin();
     242                    it != this->physicalObjectQueue_.end(); ++it)
     243                {
     244                    this->physicalWorld_->addRigidBody((*it)->physicalBody_);
     245                    this->physicalObjects_.insert(*it);
     246                }
     247                this->physicalObjectQueue_.clear();
     248            }
     249
     250            // Note: 60 means that Bullet will do physics correctly down to 1 frames per seconds.
     251            //       Under that mark, the simulation will "loose time" and get unusable.
     252            physicalWorld_->stepSimulation(dt, 60);
     253        }
    118254    }
    119255
     
    165301    }
    166302
    167     void Scene::tick(float dt)
    168     {
    169         if (!Core::showsGraphics())
    170         {
    171             // We need to update the scene nodes if we don't render
    172             this->rootSceneNode_->_update(true, false);
    173         }
     303    void Scene::addPhysicalObject(WorldEntity* object)
     304    {
     305        if (object)
     306        {
     307            std::set<WorldEntity*>::iterator it = this->physicalObjects_.find(object);
     308            if (it != this->physicalObjects_.end())
     309                return;
     310
     311            this->physicalObjectQueue_.insert(object);
     312        }
     313    }
     314
     315    void Scene::removePhysicalObject(WorldEntity* object)
     316    {
     317        // check queue first
     318        std::set<WorldEntity*>::iterator it = this->physicalObjectQueue_.find(object);
     319        if (it != this->physicalObjectQueue_.end())
     320        {
     321            this->physicalObjectQueue_.erase(it);
     322            return;
     323        }
     324
     325        it = this->physicalObjects_.find(object);
     326        if (it == this->physicalObjects_.end())
     327            return;
     328        this->physicalObjects_.erase(it);
     329
     330        if (this->hasPhysics())
     331            this->physicalWorld_->removeRigidBody(object->physicalBody_);
     332    }
     333
     334    /*static*/ bool Scene::collisionCallback(btManifoldPoint& cp, const btCollisionObject* colObj0, int partId0,
     335                                             int index0, const btCollisionObject* colObj1, int partId1, int index1)
     336    {
     337        // get the WorldEntity pointers
     338        WorldEntity* object0 = (WorldEntity*)colObj0->getUserPointer();
     339        assert(dynamic_cast<WorldEntity*>(object0));
     340        WorldEntity* object1 = (WorldEntity*)colObj1->getUserPointer();
     341        assert(dynamic_cast<WorldEntity*>(object1));
     342
     343        // false means that bullet will assume we didn't modify the contact
     344        bool modified = false;
     345        if (object0->isCollisionCallbackActive())
     346        {
     347            modified |= object0->collidesAgainst(object1, cp);
     348            if (object1->isCollisionCallbackActive())
     349                modified |= object1->collidesAgainst(object0, cp);
     350        }
     351        else
     352            modified |= object1->collidesAgainst(object0, cp);
     353
     354        return modified;
    174355    }
    175356}
  • code/trunk/src/orxonox/objects/Scene.h

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder (physics)
    2425 *   Co-authors:
    2526 *      ...
     
    3233#include "OrxonoxPrereqs.h"
    3334
    34 #include "network/Synchronisable.h"
     35#include "network/synchronisable/Synchronisable.h"
    3536#include "core/BaseObject.h"
    3637#include "util/Math.h"
     
    7576            void networkcallback_applyAmbientLight()
    7677                { this->setAmbientLight(this->ambientLight_); }
     78            void networkcallback_applyShadows()
     79                { this->setShadow(this->bShadows_); }
    7780
    78             Ogre::SceneManager*    sceneManager_;
    79             Ogre::SceneNode*       rootSceneNode_;
    80             std::string            skybox_;
    81             ColourValue            ambientLight_;
    82             std::list<BaseObject*> objects_;
    83             bool                   bShadows_;
     81            Ogre::SceneManager*      sceneManager_;
     82            Ogre::SceneNode*         rootSceneNode_;
     83
     84            std::string              skybox_;
     85            ColourValue              ambientLight_;
     86            std::list<BaseObject*>   objects_;
     87            bool                     bShadows_;
     88
     89
     90        /////////////
     91        // Physics //
     92        /////////////
     93
     94        public:
     95            inline bool hasPhysics()
     96                { return this->physicalWorld_ != 0; }
     97            void setPhysicalWorld(bool wantsPhysics);
     98
     99            void setNegativeWorldRange(const Vector3& range);
     100            inline const Vector3& getNegativeWorldRange() const
     101                { return this->negativeWorldRange_; }
     102
     103            void setPositiveWorldRange(const Vector3& range);
     104            inline const Vector3& getPositiveWorldRange() const
     105                { return this->positiveWorldRange_; }
     106
     107            void setGravity(const Vector3& gravity);
     108            inline const Vector3& getGravity() const
     109                { return this->gravity_; }
     110
     111            void addPhysicalObject(WorldEntity* object);
     112            void removePhysicalObject(WorldEntity* object);
     113
     114        private:
     115            inline void networkcallback_hasPhysics()
     116                { this->setPhysicalWorld(this->bHasPhysics_); }
     117            inline void networkcallback_negativeWorldRange()
     118                { this->setNegativeWorldRange(this->negativeWorldRange_); }
     119            inline void networkcallback_positiveWorldRange()
     120                { this->setPositiveWorldRange(this->positiveWorldRange_); }
     121            inline void networkcallback_gravity()
     122                { this->setGravity(this->gravity_); }
     123
     124            // collision callback from bullet
     125            static bool collisionCallback(btManifoldPoint& cp, const btCollisionObject* colObj0, int partId0,
     126                                          int index0, const btCollisionObject* colObj1, int partId1, int index1);
     127
     128            // Bullet objects
     129            btDiscreteDynamicsWorld*             physicalWorld_;
     130            bt32BitAxisSweep3*                   broadphase_;
     131            btDefaultCollisionConfiguration*     collisionConfig_;
     132            btCollisionDispatcher*               dispatcher_;
     133            btSequentialImpulseConstraintSolver* solver_;
     134
     135            std::set<WorldEntity*>               physicalObjectQueue_;
     136            std::set<WorldEntity*>               physicalObjects_;
     137            bool                                 bHasPhysics_;
     138            Vector3                              negativeWorldRange_;
     139            Vector3                              positiveWorldRange_;
     140            Vector3                              gravity_;
    84141    };
    85142}
  • code/trunk/src/orxonox/objects/Script.cc

    r2087 r2662  
    6464  void Script::execute()
    6565  {
    66     LuaBind* lua = LuaBind::getInstance();
    67     lua->loadString(this->code_);
    68     lua->run();
     66    LuaBind& lua = LuaBind::getInstance();
     67    lua.loadString(this->code_);
     68    lua.run();
    6969  }
    7070}
  • code/trunk/src/orxonox/objects/Test.cc

    r2171 r2662  
    6161        void Test::setConfigValues()
    6262        {
    63                 SetConfigValue ( v1, 1 )/*.callback ( this, &Test::checkV1 )*/;
    64     SetConfigValue ( v2, 2 )/*.callback ( this, &Test::checkV2 )*/;
    65     SetConfigValue ( v3, 3 )/*.callback ( this, &Test::checkV3 )*/;
    66     SetConfigValue ( v4, 4 )/*.callback ( this, &Test::checkV4 )*/;
     63                SetConfigValue ( u1, 1 )/*.callback ( this, &Test::checkV1 )*/;
     64    SetConfigValue ( u2, 2 )/*.callback ( this, &Test::checkV2 )*/;
     65    SetConfigValue ( u3, 3 )/*.callback ( this, &Test::checkV3 )*/;
     66    SetConfigValue ( u4, 4 )/*.callback ( this, &Test::checkV4 )*/;
     67   
     68    SetConfigValue ( s1, 1 )/*.callback ( this, &Test::checkV1 )*/;
     69    SetConfigValue ( s2, 2 )/*.callback ( this, &Test::checkV2 )*/;
     70    SetConfigValue ( s3, 3 )/*.callback ( this, &Test::checkV3 )*/;
     71    SetConfigValue ( s4, 4 )/*.callback ( this, &Test::checkV4 )*/;
    6772        }
    6873
     
    7075        void Test::registerVariables()
    7176        {
    72                 REGISTERDATA ( v1,direction::toclient, new NetworkCallback<Test> ( this, &Test::checkV1 ) );
    73     REGISTERDATA ( v2,direction::toserver, new NetworkCallback<Test> ( this, &Test::checkV2 ) );
    74                 REGISTERDATA ( v3,direction::serverMaster, new NetworkCallback<Test> ( this, &Test::checkV3 ) );
    75     REGISTERDATA ( v4,direction::clientMaster, new NetworkCallback<Test> ( this, &Test::checkV4 ) );
     77                registerVariable ( u1, variableDirection::toclient, new NetworkCallback<Test> ( this, &Test::checkU1 ));
     78    registerVariable ( u2, variableDirection::toserver, new NetworkCallback<Test> ( this, &Test::checkU2 ));
     79                registerVariable ( u3, variableDirection::serverMaster, new NetworkCallback<Test> ( this, &Test::checkU3 ), true );
     80    registerVariable ( u4, variableDirection::clientMaster, new NetworkCallback<Test> ( this, &Test::checkU4 ), true );
     81   
     82    registerVariable ( s1, variableDirection::toclient, new NetworkCallback<Test> ( this, &Test::checkS1 ));
     83    registerVariable ( s2, variableDirection::toserver, new NetworkCallback<Test> ( this, &Test::checkS2 ));
     84    registerVariable ( s3, variableDirection::serverMaster, new NetworkCallback<Test> ( this, &Test::checkS3 ), true );
     85    registerVariable ( s4, variableDirection::clientMaster, new NetworkCallback<Test> ( this, &Test::checkS4 ), true );
    7686        }
    7787
    78   void Test::checkV1(){
    79     COUT(1) << "V1 changed: " << v1 << std::endl;
    80   }
     88  void Test::checkU1(){ COUT(1) << "U1 changed: " << u1 << std::endl; }
     89  void Test::checkU2(){ COUT(1) << "U2 changed: " << u2 << std::endl; }
     90  void Test::checkU3(){ COUT(1) << "U3 changed: " << u3 << std::endl; }
     91  void Test::checkU4(){ COUT(1) << "U4 changed: " << u4 << std::endl; }
    8192
    82   void Test::checkV2(){
    83     COUT(1) << "V2 changed: " << v2 << std::endl;
    84   }
    85 
    86   void Test::checkV3(){
    87     COUT(1) << "V3 changed: " << v3 << std::endl;
    88   }
    89  
    90   void Test::checkV4(){
    91     COUT(1) << "V4 changed: " << v4 << std::endl;
    92   }
    93 
     93  void Test::checkS1(){ COUT(1) << "S1 changed: " << s1 << std::endl; }
     94  void Test::checkS2(){ COUT(1) << "S2 changed: " << s2 << std::endl; }
     95  void Test::checkS3(){ COUT(1) << "S3 changed: " << s3 << std::endl; }
     96  void Test::checkS4(){ COUT(1) << "S4 changed: " << s4 << std::endl; }
    9497
    9598}
  • code/trunk/src/orxonox/objects/Test.h

    r2171 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333#include "core/BaseObject.h"
    34 #include "network/Synchronisable.h"
     34#include "network/synchronisable/Synchronisable.h"
     35
     36
     37typedef int TYPE;
     38typedef unsigned int UTYPE;
     39
    3540
    3641namespace orxonox
     
    4550      void registerVariables();
    4651
    47       void setV1(unsigned int value){ v1 = value; }
    48       void setV2(unsigned int value){ v2 = value; }
    49       void setV3(unsigned int value){ v3 = value; }
    50       void setV4(unsigned int value){ v4 = value; }
    5152
    52       void checkV1();
    53       void checkV2();
    54       void checkV3();
    55       void checkV4();
     53      //unsigned functions
     54      void setU1(UTYPE value){ u1 = value; }
     55      void setU2(UTYPE value){ u2 = value; }
     56      void setU3(UTYPE value){ u3 = value; }
     57      void setU4(UTYPE value){ u4 = value; }
     58      void checkU1();
     59      void checkU2();
     60      void checkU3();
     61      void checkU4();
    5662     
    57       void printV1(){ instance_->checkV1(); }
    58       void printV2(){ instance_->checkV2(); }
    59       void printV3(){ instance_->checkV3(); }
    60       void printV4(){ instance_->checkV4(); }
     63      //signed functions
     64      void setS1(TYPE value){ s1 = value; }
     65      void setS2(TYPE value){ s2 = value; }
     66      void setS3(TYPE value){ s3 = value; }
     67      void setS4(TYPE value){ s4 = value; }
     68      void checkS1();
     69      void checkS2();
     70      void checkS3();
     71      void checkS4();
     72     
     73      static void printV1(){ instance_->checkU1(); }
     74      static void printV2(){ instance_->checkU2(); }
     75      static void printV3(){ instance_->checkU3(); }
     76      static void printV4(){ instance_->checkU4(); }
    6177
    6278    private:
    63       unsigned int v1;
    64       unsigned int v2;
    65       unsigned int v3;
    66       unsigned int v4;
     79      UTYPE u1;
     80      UTYPE u2;
     81      UTYPE u3;
     82      UTYPE u4;
     83     
     84      TYPE s1;
     85      TYPE s2;
     86      TYPE s3;
     87      TYPE s4;
    6788     
    6889      static Test* instance_;
  • code/trunk/src/orxonox/objects/collisionshapes

  • code/trunk/src/orxonox/objects/controllers/CMakeLists.txt

    r2131 r2662  
    22  Controller.cc
    33  HumanController.cc
     4  ArtificialController.cc
     5  AIController.cc
     6  ScriptController.cc
    47)
    58
  • code/trunk/src/orxonox/objects/controllers/Controller.cc

    r2087 r2662  
    3131
    3232#include "core/CoreIncludes.h"
     33#include "overlays/OverlayGroup.h"
    3334
    3435namespace orxonox
     
    4243        this->player_ = 0;
    4344        this->controllableEntity_ = 0;
     45        this->hud_ = 0;
     46        this->bUpdateHUD_ = false;
    4447    }
    4548
    4649    Controller::~Controller()
    4750    {
     51        if (this->isInitialized() && this->hud_)
     52            delete this->hud_;
     53    }
     54
     55    void Controller::changedControllableEntity()
     56    {
     57        if (this->bUpdateHUD_)
     58        {
     59            this->updateHUD();
     60            this->bUpdateHUD_ = false;
     61        }
     62
     63        if (this->hud_)
     64            this->hud_->setOwner(this->getControllableEntity());
     65    }
     66
     67    void Controller::updateHUD()
     68    {
     69        if (this->hud_)
     70        {
     71            delete this->hud_;
     72            this->hud_ = 0;
     73        }
     74
     75        if (this->hudtemplate_ != "")
     76        {
     77            this->hud_ = new OverlayGroup(this);
     78            this->hud_->addTemplate(this->hudtemplate_);
     79            this->hud_->setOwner(this->getControllableEntity());
     80        }
    4881    }
    4982}
  • code/trunk/src/orxonox/objects/controllers/Controller.h

    r2087 r2662  
    4747                { return this->player_; }
    4848
    49             virtual inline void setControllableEntity(ControllableEntity* entity)
    50                 { this->controllableEntity_ = entity; }
    51             virtual inline ControllableEntity* getControllableEntity() const
     49            inline void setControllableEntity(ControllableEntity* entity)
     50            {
     51                if (entity != this->controllableEntity_)
     52                {
     53                    this->controllableEntity_ = entity;
     54                    this->changedControllableEntity();
     55                }
     56            }
     57            inline ControllableEntity* getControllableEntity() const
    5258                { return this->controllableEntity_; }
     59            virtual void changedControllableEntity();
     60
     61            inline void setHUDTemplate(const std::string& name)
     62            {
     63                if (name != this->hudtemplate_)
     64                {
     65                    this->hudtemplate_ = name;
     66                    if (this->controllableEntity_)
     67                        this->updateHUD();
     68                    else
     69                        this->bUpdateHUD_ = true;
     70                }
     71            }
     72            inline const std::string& getHUDTemplate() const
     73                { return this->hudtemplate_; }
     74
     75            inline OverlayGroup* getHUD() const
     76                { return this->hud_; }
    5377
    5478        protected:
     79            void updateHUD();
     80
    5581            PlayerInfo* player_;
    5682            ControllableEntity* controllableEntity_;
     83            std::string hudtemplate_;
     84            OverlayGroup* hud_;
     85            bool bUpdateHUD_;
    5786    };
    5887}
  • code/trunk/src/orxonox/objects/controllers/HumanController.cc

    r2087 r2662  
    3333#include "core/ConsoleCommand.h"
    3434#include "objects/worldentities/ControllableEntity.h"
     35#include "objects/worldentities/pawns/Pawn.h"
     36#include "objects/gametypes/Gametype.h"
    3537
    3638namespace orxonox
     
    4446    SetConsoleCommand(HumanController, fire,          true).keybindMode(KeybindMode::OnHold);
    4547    SetConsoleCommand(HumanController, altFire,       true).keybindMode(KeybindMode::OnHold);
     48    SetConsoleCommand(HumanController, boost,         true).keybindMode(KeybindMode::OnHold);
    4649    SetConsoleCommand(HumanController, greet,         true);
    4750    SetConsoleCommand(HumanController, use,           true);
    4851    SetConsoleCommand(HumanController, switchCamera,  true);
     52    SetConsoleCommand(HumanController, mouseLook,     true);
     53    SetConsoleCommand(HumanController, suicide,       true);
     54    SetConsoleCommand(HumanController, addBots,       true).defaultValues(1);
     55    SetConsoleCommand(HumanController, killBots,      true).defaultValues(0);
     56    SetConsoleCommand(HumanController, dropItems,     true);
    4957
    5058    CreateUnloadableFactory(HumanController);
     
    103111    {
    104112        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
    105             HumanController::localController_s->controllableEntity_->fire();
     113            HumanController::localController_s->controllableEntity_->fire(WeaponMode::fire);
    106114    }
    107115
     
    109117    {
    110118        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
    111             HumanController::localController_s->controllableEntity_->altFire();
     119            HumanController::localController_s->controllableEntity_->fire(WeaponMode::altFire);
     120    }
     121
     122    void HumanController::boost()
     123    {
     124        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
     125            HumanController::localController_s->controllableEntity_->boost();
    112126    }
    113127
     
    129143            HumanController::localController_s->controllableEntity_->switchCamera();
    130144    }
     145
     146    void HumanController::mouseLook()
     147    {
     148        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
     149            HumanController::localController_s->controllableEntity_->mouseLook();
     150    }
     151
     152    void HumanController::suicide()
     153    {
     154        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
     155        {
     156            Pawn* pawn = dynamic_cast<Pawn*>(HumanController::localController_s->controllableEntity_);
     157            if (pawn)
     158                pawn->kill();
     159        }
     160    }
     161
     162    void HumanController::addBots(unsigned int amount)
     163    {
     164        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_ && HumanController::localController_s->controllableEntity_->getGametype())
     165            HumanController::localController_s->controllableEntity_->getGametype()->addBots(amount);
     166    }
     167
     168    void HumanController::killBots(unsigned int amount)
     169    {
     170        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_ && HumanController::localController_s->controllableEntity_->getGametype())
     171            HumanController::localController_s->controllableEntity_->getGametype()->killBots(amount);
     172    }
     173
     174    void HumanController::dropItems()
     175    {
     176        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
     177            HumanController::localController_s->controllableEntity_->dropItems();
     178    }
    131179}
  • code/trunk/src/orxonox/objects/controllers/HumanController.h

    r2087 r2662  
    5454            static void altFire();
    5555
     56            static void boost();
    5657            static void greet();
    5758            static void use();
    5859            static void switchCamera();
     60            static void mouseLook();
     61            static void dropItems();
     62
     63            static void suicide();
     64
     65            static void addBots(unsigned int amount);
     66            static void killBots(unsigned int amount = 0);
    5967
    6068        private:
  • code/trunk/src/orxonox/objects/gametypes/Gametype.cc

    r2171 r2662  
    3434
    3535#include "core/CoreIncludes.h"
     36#include "core/ConfigValueIncludes.h"
     37#include "core/Template.h"
     38#include "core/Core.h"
     39#include "overlays/OverlayGroup.h"
    3640#include "objects/infos/PlayerInfo.h"
     41#include "objects/infos/Bot.h"
    3742#include "objects/worldentities/pawns/Spectator.h"
    3843#include "objects/worldentities/SpawnPoint.h"
     44#include "objects/worldentities/Camera.h"
     45#include "Settings.h"
    3946
    4047#include "network/Host.h"
     
    4451    CreateUnloadableFactory(Gametype);
    4552
    46     Gametype::Gametype(BaseObject* creator) : BaseObject(creator)
     53    Gametype::Gametype(BaseObject* creator) : BaseObject(creator), gtinfo_(creator)
    4754    {
    4855        RegisterObject(Gametype);
    4956
     57        this->setGametype(this);
     58
    5059        this->defaultControllableEntity_ = Class(Spectator);
    5160
    52         this->bStarted_ = false;
    53         this->bEnded_ = false;
    5461        this->bAutoStart_ = false;
    5562        this->bForceSpawn_ = false;
     63        this->numberOfBots_ = 0;
    5664
    5765        this->initialStartCountdown_ = 3;
    58         this->startCountdown_ = 0;
    59         this->bStartCountdownRunning_ = false;
     66
     67        this->setConfigValues();
     68
     69        this->addBots(this->numberOfBots_);
     70
     71        // load the corresponding score board
     72        if (Core::showsGraphics() && this->scoreboardTemplate_ != "")
     73        {
     74            this->scoreboard_ = new OverlayGroup(this);
     75            this->scoreboard_->addTemplate(this->scoreboardTemplate_);
     76            this->scoreboard_->setGametype(this);
     77        }
     78        else
     79            this->scoreboard_ = 0;
     80    }
     81
     82    void Gametype::setConfigValues()
     83    {
     84        SetConfigValue(initialStartCountdown_, 3.0f);
     85        SetConfigValue(bAutoStart_, false);
     86        SetConfigValue(bForceSpawn_, false);
     87        SetConfigValue(numberOfBots_, 0);
     88        SetConfigValue(scoreboardTemplate_, "defaultScoreboard");
    6089    }
    6190
    6291    void Gametype::tick(float dt)
    6392    {
    64         if (this->bStartCountdownRunning_ && !this->bStarted_)
    65             this->startCountdown_ -= dt;
    66 
    67         if (!this->bStarted_)
     93        SUPER(Gametype, tick, dt);
     94
     95        if (this->gtinfo_.bStartCountdownRunning_ && !this->gtinfo_.bStarted_)
     96            this->gtinfo_.startCountdown_ -= dt;
     97
     98        if (!this->gtinfo_.bStarted_)
    6899            this->checkStart();
    69100        else
     
    76107    {
    77108        COUT(0) << "game started" << std::endl;
    78         this->bStarted_ = true;
     109        this->gtinfo_.bStarted_ = true;
    79110
    80111        this->spawnPlayersIfRequested();
     
    84115    {
    85116        COUT(0) << "game ended" << std::endl;
    86         this->bEnded_ = true;
     117        this->gtinfo_.bEnded_ = true;
    87118    }
    88119
    89120    void Gametype::playerEntered(PlayerInfo* player)
    90121    {
    91         this->players_[player] = PlayerState::Joined;
     122        this->players_[player].state_ = PlayerState::Joined;
    92123
    93124        std::string message = player->getName() + " entered the game";
     
    98129    void Gametype::playerLeft(PlayerInfo* player)
    99130    {
    100         std::map<PlayerInfo*, PlayerState::Enum>::iterator it = this->players_.find(player);
     131        std::map<PlayerInfo*, Player>::iterator it = this->players_.find(player);
    101132        if (it != this->players_.end())
    102133        {
     
    140171    void Gametype::pawnKilled(Pawn* victim, Pawn* killer)
    141172    {
    142     }
    143 
    144     void Gametype::playerScored(PlayerInfo* player)
    145     {
     173        if (victim && victim->getPlayer())
     174        {
     175            std::string message;
     176            if (killer)
     177            {
     178                if (killer->getPlayer())
     179                    message = victim->getPlayer()->getName() + " was killed by " + killer->getPlayer()->getName();
     180                else
     181                    message = victim->getPlayer()->getName() + " was killed";
     182            }
     183            else
     184                message = victim->getPlayer()->getName() + " died";
     185
     186            COUT(0) << message << std::endl;
     187            Host::Broadcast(message);
     188        }
     189
     190        if (victim && victim->getPlayer())
     191        {
     192            std::map<PlayerInfo*, Player>::iterator it = this->players_.find(victim->getPlayer());
     193            if (it != this->players_.end())
     194            {
     195                it->second.state_ = PlayerState::Dead;
     196                it->second.killed_++;
     197
     198                // Reward killer
     199                if (killer)
     200                {
     201                    std::map<PlayerInfo*, Player>::iterator itKiller = this->players_.find(killer->getPlayer());
     202                    if (itKiller != this->players_.end())
     203                    {
     204                        this->playerScored(itKiller->second);
     205                    }
     206                    else
     207                        COUT(2) << "Warning: Killing Pawn was not in the playerlist" << std::endl;
     208                }
     209
     210                ControllableEntity* entity = this->defaultControllableEntity_.fabricate(victim->getCreator());
     211                if (victim->getCamera())
     212                {
     213                    entity->setPosition(victim->getCamera()->getWorldPosition());
     214                    entity->setOrientation(victim->getCamera()->getWorldOrientation());
     215                }
     216                else
     217                {
     218                    entity->setPosition(victim->getWorldPosition());
     219                    entity->setOrientation(victim->getWorldOrientation());
     220                }
     221                it->first->startControl(entity);
     222            }
     223            else
     224                COUT(2) << "Warning: Killed Pawn was not in the playerlist" << std::endl;
     225        }
     226    }
     227
     228    void Gametype::playerScored(Player& player)
     229    {
     230        player.frags_++;
    146231    }
    147232
     
    150235        if (this->spawnpoints_.size() > 0)
    151236        {
    152             srand(time(0));
    153             rnd();
    154 
    155237            unsigned int randomspawn = (unsigned int)rnd(this->spawnpoints_.size());
    156238            unsigned int index = 0;
     
    168250    void Gametype::assignDefaultPawnsIfNeeded()
    169251    {
    170         for (std::map<PlayerInfo*, PlayerState::Enum>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
    171         {
    172             if (!it->first->getControllableEntity() && (!it->first->isReadyToSpawn() || !this->bStarted_))
    173             {
    174                 SpawnPoint* spawn = this->getBestSpawnPoint(it->first);
    175                 if (spawn)
    176                 {
    177                     // force spawn at spawnpoint with default pawn
    178                     ControllableEntity* entity = this->defaultControllableEntity_.fabricate(spawn);
    179                     spawn->spawn(entity);
    180                     it->first->startControl(entity);
    181                     it->second = PlayerState::Dead;
     252        for (std::map<PlayerInfo*, Player>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
     253        {
     254            if (!it->first->getControllableEntity())
     255            {
     256                it->second.state_ = PlayerState::Dead;
     257
     258                if (!it->first->isReadyToSpawn() || !this->gtinfo_.bStarted_)
     259                {
     260                    SpawnPoint* spawn = this->getBestSpawnPoint(it->first);
     261                    if (spawn)
     262                    {
     263                        // force spawn at spawnpoint with default pawn
     264                        ControllableEntity* entity = this->defaultControllableEntity_.fabricate(spawn);
     265                        spawn->spawn(entity);
     266                        it->first->startControl(entity);
     267                        it->second.state_ = PlayerState::Dead;
     268                    }
     269                    else
     270                    {
     271                        COUT(1) << "Error: No SpawnPoints in current Gametype" << std::endl;
     272                        abort();
     273                    }
     274                }
     275            }
     276        }
     277    }
     278
     279    void Gametype::checkStart()
     280    {
     281        if (!this->gtinfo_.bStarted_)
     282        {
     283            if (this->gtinfo_.bStartCountdownRunning_)
     284            {
     285                if (this->gtinfo_.startCountdown_ <= 0)
     286                {
     287                    this->gtinfo_.bStartCountdownRunning_ = false;
     288                    this->gtinfo_.startCountdown_ = 0;
     289                    this->start();
     290                }
     291            }
     292            else if (this->players_.size() > 0)
     293            {
     294                if (this->bAutoStart_)
     295                {
     296                    this->start();
    182297                }
    183298                else
    184299                {
    185                     COUT(1) << "Error: No SpawnPoints in current Gametype" << std::endl;
    186                     abort();
    187                 }
    188             }
    189         }
    190     }
    191 
    192     void Gametype::checkStart()
    193     {
    194         if (!this->bStarted_)
    195         {
    196             if (this->bStartCountdownRunning_)
    197             {
    198                 if (this->startCountdown_ <= 0)
    199                 {
    200                     this->bStartCountdownRunning_ = false;
    201                     this->startCountdown_ = 0;
    202                     this->start();
    203                 }
    204             }
    205             else if (this->players_.size() > 0)
    206             {
    207                 if (this->bAutoStart_)
    208                 {
    209                     this->start();
    210                 }
    211                 else
    212                 {
    213300                    bool allplayersready = true;
    214                     for (std::map<PlayerInfo*, PlayerState::Enum>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
     301                    bool hashumanplayers = false;
     302                    for (std::map<PlayerInfo*, Player>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
    215303                    {
    216304                        if (!it->first->isReadyToSpawn())
    217305                            allplayersready = false;
    218                     }
    219                     if (allplayersready)
    220                     {
    221                         this->startCountdown_ = this->initialStartCountdown_;
    222                         this->bStartCountdownRunning_ = true;
     306                        if (it->first->isHumanPlayer())
     307                            hashumanplayers = true;
     308                    }
     309                    if (allplayersready && hashumanplayers)
     310                    {
     311                        this->gtinfo_.startCountdown_ = this->initialStartCountdown_;
     312                        this->gtinfo_.bStartCountdownRunning_ = true;
    223313                    }
    224314                }
     
    229319    void Gametype::spawnPlayersIfRequested()
    230320    {
    231         for (std::map<PlayerInfo*, PlayerState::Enum>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
     321        for (std::map<PlayerInfo*, Player>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
    232322            if (it->first->isReadyToSpawn() || this->bForceSpawn_)
    233323                this->spawnPlayer(it->first);
     
    236326    void Gametype::spawnDeadPlayersIfRequested()
    237327    {
    238         for (std::map<PlayerInfo*, PlayerState::Enum>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
    239             if (it->second == PlayerState::Dead)
     328        for (std::map<PlayerInfo*, Player>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
     329            if (it->second.state_ == PlayerState::Dead)
    240330                if (it->first->isReadyToSpawn() || this->bForceSpawn_)
    241331                    this->spawnPlayer(it->first);
     
    248338        {
    249339            player->startControl(spawnpoint->spawn());
    250             this->players_[player] = PlayerState::Alive;
     340            this->players_[player].state_ = PlayerState::Alive;
    251341        }
    252342        else
     
    256346        }
    257347    }
     348
     349    void Gametype::addBots(unsigned int amount)
     350    {
     351        for (unsigned int i = 0; i < amount; ++i)
     352            new Bot(this);
     353    }
     354
     355    void Gametype::killBots(unsigned int amount)
     356    {
     357        unsigned int i = 0;
     358        for (ObjectList<Bot>::iterator it = ObjectList<Bot>::begin(); (it != ObjectList<Bot>::end()) && ((amount == 0) || (i < amount)); )
     359        {
     360            if (it->getGametype() == this)
     361            {
     362                delete (*(it++));
     363                ++i;
     364            }
     365        }
     366    }
    258367}
  • code/trunk/src/orxonox/objects/gametypes/Gametype.h

    r2171 r2662  
    3838#include "objects/worldentities/ControllableEntity.h"
    3939#include "objects/Tickable.h"
     40#include "objects/infos/GametypeInfo.h"
    4041
    4142namespace orxonox
     
    5253    }
    5354
     55    struct Player
     56    {
     57        PlayerInfo* info_;
     58        PlayerState::Enum state_;
     59        int frags_;
     60        int killed_;
     61    };
     62
    5463    class _OrxonoxExport Gametype : public BaseObject, public Tickable
    5564    {
     
    6069            virtual ~Gametype() {}
    6170
     71            void setConfigValues();
     72
    6273            virtual void tick(float dt);
    6374
     75            inline const GametypeInfo* getGametypeInfo() const
     76                { return &this->gtinfo_; }
     77
    6478            inline bool hasStarted() const
    65                 { return this->bStarted_; }
     79                { return this->gtinfo_.bStarted_; }
    6680            inline bool hasEnded() const
    67                 { return this->bEnded_; }
     81                { return this->gtinfo_.bEnded_; }
    6882
    6983            virtual void start();
     
    7589            virtual void playerChangedName(PlayerInfo* player);
    7690
    77             virtual void playerScored(PlayerInfo* player);
     91            virtual void playerScored(Player& player);
    7892
    7993            virtual void pawnKilled(Pawn* victim, Pawn* killer = 0);
     
    8195            virtual void pawnPostSpawn(Pawn* pawn);
    8296
    83             inline const std::map<PlayerInfo*, PlayerState::Enum>& getPlayers() const
     97            inline const std::map<PlayerInfo*, Player>& getPlayers() const
    8498                { return this->players_; }
    8599
     
    88102
    89103            inline bool isStartCountdownRunning() const
    90                 { return this->bStartCountdownRunning_; }
     104                { return this->gtinfo_.bStartCountdownRunning_; }
    91105            inline float getStartCountdown() const
    92                 { return this->startCountdown_; }
     106                { return this->gtinfo_.startCountdown_; }
     107
     108            void addBots(unsigned int amount);
     109            void killBots(unsigned int amount = 0);
     110
     111            inline unsigned int getNumberOfPlayers() const
     112                { return this->players_.size(); }
    93113
    94114        private:
     
    104124            void spawnDeadPlayersIfRequested();
    105125
    106             bool bStarted_;
    107             bool bEnded_;
     126            GametypeInfo gtinfo_;
     127
    108128            bool bAutoStart_;
    109129            bool bForceSpawn_;
    110130
    111131            float initialStartCountdown_;
    112             float startCountdown_;
    113             bool bStartCountdownRunning_;
     132            unsigned int numberOfBots_;
    114133
    115             std::map<PlayerInfo*, PlayerState::Enum> players_;
     134            std::map<PlayerInfo*, Player> players_;
    116135            std::set<SpawnPoint*> spawnpoints_;
    117136            SubclassIdentifier<ControllableEntity> defaultControllableEntity_;
     137
     138            OverlayGroup* scoreboard_;
     139
     140            // Config Values
     141            std::string scoreboardTemplate_;
    118142    };
    119143}
  • code/trunk/src/orxonox/objects/infos/CMakeLists.txt

    r2171 r2662  
    11SET( SRC_FILES
     2  Bot.cc
    23  Info.cc
    34  PlayerInfo.cc
    45  HumanPlayer.cc
     6  GametypeInfo.cc
    57)
    68
  • code/trunk/src/orxonox/objects/infos/HumanPlayer.cc

    r2171 r2662  
    3737#include "objects/controllers/HumanController.h"
    3838#include "objects/gametypes/Gametype.h"
     39#include "overlays/OverlayGroup.h"
    3940
    4041namespace orxonox
     
    6364    {
    6465        SetConfigValue(nick_, "Player").callback(this, &HumanPlayer::configvaluecallback_changednick);
     66        SetConfigValue(hudtemplate_, "defaultHUD").callback(this, &HumanPlayer::configvaluecallback_changedHUDTemplate);
    6567    }
    6668
    6769    void HumanPlayer::registerVariables()
    6870    {
    69         REGISTERSTRING(this->synchronize_nick_, direction::toserver, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_changednick));
     71        registerVariable(this->synchronize_nick_, variableDirection::toserver, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_changednick));
    7072
    71         REGISTERDATA(this->clientID_,     direction::toclient, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_clientIDchanged));
    72         REGISTERDATA(this->server_initialized_, direction::toclient, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_server_initialized));
    73         REGISTERDATA(this->client_initialized_, direction::toserver, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_client_initialized));
     73        registerVariable(this->clientID_,           variableDirection::toclient, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_clientIDchanged));
     74        registerVariable(this->server_initialized_, variableDirection::toclient, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_server_initialized));
     75        registerVariable(this->client_initialized_, variableDirection::toserver, new NetworkCallback<HumanPlayer>(this, &HumanPlayer::networkcallback_client_initialized));
    7476    }
    7577
     
    8385                this->setName(this->nick_);
    8486        }
     87    }
     88
     89    void HumanPlayer::configvaluecallback_changedHUDTemplate()
     90    {
     91        this->changedController();
    8592    }
    8693
     
    99106
    100107            if (!Core::isMaster())
    101                 this->setObjectMode(direction::bidirectional);
     108                this->setObjectMode(objectDirection::bidirectional);
    102109            else
    103110                this->setName(this->nick_);
     
    138145        this->networkcallback_clientIDchanged();
    139146    }
     147
     148    void HumanPlayer::changedController()
     149    {
     150        if (this->getController())
     151        {
     152            this->getController()->setHUDTemplate(this->hudtemplate_);
     153
     154            if (this->getController() && this->getController()->getHUD())
     155                this->getController()->getHUD()->setOwner(this->getControllableEntity());
     156        }
     157    }
    140158}
  • code/trunk/src/orxonox/objects/infos/HumanPlayer.h

    r2171 r2662  
    3333
    3434#include "PlayerInfo.h"
    35 #include "core/Identifier.h"
    36 #include "objects/controllers/Controller.h"
    3735
    3836namespace orxonox
     
    5351            void setClientID(unsigned int clientID);
    5452
     53            virtual void changedController();
     54
    5555        protected:
    5656            void configvaluecallback_changednick();
     57            void configvaluecallback_changedHUDTemplate();
    5758            void networkcallback_changednick();
    5859            void networkcallback_clientIDchanged();
     
    6263            std::string nick_;
    6364            std::string synchronize_nick_;
     65            std::string hudtemplate_;
    6466            bool server_initialized_;
    6567            bool client_initialized_;
  • code/trunk/src/orxonox/objects/infos/Info.h

    r2171 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333
    34 #include "network/Synchronisable.h"
     34#include "network/synchronisable/Synchronisable.h"
    3535#include "core/BaseObject.h"
    3636
  • code/trunk/src/orxonox/objects/infos/PlayerInfo.cc

    r2171 r2662  
    4646        this->bLocalPlayer_ = false;
    4747        this->bReadyToSpawn_ = false;
     48        this->bSetUnreadyAfterSpawn_ = true;
    4849        this->controller_ = 0;
    4950        this->controllableEntity_ = 0;
     
    6465                this->controller_ = 0;
    6566            }
     67
     68            if (this->getGametype())
     69                this->getGametype()->playerLeft(this);
    6670        }
    6771    }
     
    6973    void PlayerInfo::registerVariables()
    7074    {
    71         REGISTERSTRING(this->name_,                 direction::toclient, new NetworkCallback<PlayerInfo>(this, &PlayerInfo::changedName));
    72         REGISTERDATA  (this->controllableEntityID_, direction::toclient, new NetworkCallback<PlayerInfo>(this, &PlayerInfo::networkcallback_changedcontrollableentityID));
    73         REGISTERDATA  (this->bReadyToSpawn_,        direction::toserver);
     75        registerVariable(this->name_,                 variableDirection::toclient, new NetworkCallback<PlayerInfo>(this, &PlayerInfo::changedName));
     76        registerVariable(this->controllableEntityID_, variableDirection::toclient, new NetworkCallback<PlayerInfo>(this, &PlayerInfo::networkcallback_changedcontrollableentityID));
     77        registerVariable(this->bReadyToSpawn_,        variableDirection::toserver);
    7478    }
    7579
    7680    void PlayerInfo::changedName()
    7781    {
     82        SUPER(PlayerInfo, changedName);
     83
    7884        if (this->isInitialized() && this->getGametype())
    7985            this->getGametype()->playerChangedName(this);
     
    109115        if (this->controllableEntity_)
    110116            this->controller_->setControllableEntity(this->controllableEntity_);
     117        this->changedController();
    111118    }
    112119
    113     void PlayerInfo::startControl(ControllableEntity* entity)
     120    void PlayerInfo::startControl(ControllableEntity* entity, bool callback)
    114121    {
     122        if (entity == this->controllableEntity_)
     123            return;
     124
    115125        if (this->controllableEntity_)
    116             this->stopControl(this->controllableEntity_);
     126            this->stopControl(this->controllableEntity_, callback);
    117127
    118128        this->controllableEntity_ = entity;
     
    122132            this->controllableEntityID_ = entity->getObjectID();
    123133            entity->setPlayer(this);
    124             this->bReadyToSpawn_ = false;
     134            this->bReadyToSpawn_ &= (!this->bSetUnreadyAfterSpawn_);
    125135        }
    126136        else
  • code/trunk/src/orxonox/objects/infos/PlayerInfo.h

    r2171 r2662  
    6565                { return this->bReadyToSpawn_; }
    6666
    67             void startControl(ControllableEntity* entity);
     67            void startControl(ControllableEntity* entity, bool callback = true);
    6868            void stopControl(ControllableEntity* entity, bool callback = true);
    6969
     
    7171                { return this->controllableEntity_; }
    7272
     73            inline Controller* getController() const
     74                { return this->controller_; }
     75            virtual void changedController() {}
     76
    7377        protected:
    7478            void createController();
    75             void networkcallback_changedcontrollableentityID();
    7679
    7780            bool bHumanPlayer_;
    7881            bool bLocalPlayer_;
     82            bool bSetUnreadyAfterSpawn_;
     83            SubclassIdentifier<Controller> defaultController_;
     84            unsigned int clientID_;
     85
     86        private:
     87            void networkcallback_changedcontrollableentityID();
     88
    7989            bool bReadyToSpawn_;
    80             SubclassIdentifier<Controller> defaultController_;
    8190            Controller* controller_;
    8291            ControllableEntity* controllableEntity_;
    8392            unsigned int controllableEntityID_;
    84             unsigned int clientID_;
    8593    };
    8694}
  • code/trunk/src/orxonox/objects/pickup/CMakeLists.txt

    r2131 r2662  
    11SET( SRC_FILES
    2   ShipEquipmentClasses.cc
    3   ShipItem.cc
     2  PickupSpawner.cc
     3  BaseItem.cc
     4  Turbo.cc
     5  ShipEquipment.cc
    46)
    57
  • code/trunk/src/orxonox/objects/pickup/ShipEquipment.h

    r2094 r2662  
    1 
    21#ifndef _ShipEquipment_H__
    32#define _ShipEquipment_H__
    43#include <string>
    5 #include <multimap>
     4#include <map>
     5
     6/*
     7multimap<std::string, BaseItem*> equipment_;
     8equipment_.insert(pair<std::string, BaseItem*>("Weapon", new BaseItem()));*/
    69
    710
    8 /*
    9 multimap<std::string, Item*> equipment_;
    10 equipment_.insert(pair<std::string, Item*>("Weapon", new Item()));*/
     11/*          std::map<std::itemtype, BaseItem*> EQClasses;
     12            EQClasses["jacke"] = 0;
     13            BaseItem* item = itemMap_["jacke"];
    1114
    12 
     15           if (itemMap_["jacke"])
     16           if (itemMap_.find("jacke") != itemMap_.end()) */
    1317namespace orxonox
    1418{
     19    class BaseItem;
     20/**
     21@brief
     22    ShipEquipment is the inventory of a player. It's part of the Pawn class.
     23
     24*/
    1525    class _OrxonoxExport ShipEquipment
    1626    {
    1727        public:
    18             void AddItem(Shipitem toAddItem);
    19             void RemoveItem(Shipitem toRemoveItem);
    20             bool CheckifValid(Shipitem toBeChecked);
    21             int
    22 
     28        inline int getSpace()
     29        {
     30        return Usable.size()+Trunk.size();
     31        };
     32        bool insert(BaseItem* item);
     33        bool erase (BaseItem* item);
     34        //void print(std::multimap<std::string, BaseItem*> eut);
     35        void eraseAll();
     36        //bool checkSlot(BaseItem* item);
     37        BaseItem* checkSlot(BaseItem* item);
     38//      const std::multimap<std::string, BaseItem*>& getEquipment() const { return this->Equipment; }
     39        inline std::multimap<std::string, BaseItem*>& getEquipment() {return this->Equipment;}
     40        inline std::multimap<std::string, BaseItem*>& getUsable() {return this->Usable;}
     41        inline std::multimap<std::string, BaseItem*>& getTrunk() {return this->Trunk;}
     42        inline Pawn* getPlayer() {return this->player ;}
     43        inline void setPlayer(Pawn* setplayer)
     44        {this->player = setplayer;}
    2345        private:
    24             std::multimap<std::string, Item*> Equipment;
     46            Pawn* player;//!< Is a pointer to the belonging player
     47            std::multimap<std::string, BaseItem*> Equipment;//!< the Equipment for permanent Items
     48            std::multimap<std::string, BaseItem*> Usable;//!< Where Usables are stored
     49            std::multimap<std::string, BaseItem*> Trunk;//!< Every other Item is stored here
    2550    };
    2651}
     
    3964
    4065
    41 
    42 
    43 
    44 
    4566#endif
  • code/trunk/src/orxonox/objects/pickup/ShipEquipmentClasses.cc

    r2094 r2662  
    5757                }
    5858                break;
    59             default:;
    6059            }
    6160        case Useable:
    6261            return CheckifSpace();
    63         case default:;
    6462        }
    6563        return true;
     
    6765
    6866    /*Adds the Item to the Ship*/
    69     void ShipEquipment::AddItem(Shipitem* toAddItem)
     67    void ShipEquipment::AddItem(ShipItem* toAddItem)
    7068    {
    7169        if(CheckifValid(toAddItem)==true)
     
    9088        }
    9189    }
     90
     91    /*Adds the Item to the Ship*/
     92    void ShipEquipment::AddItem(Shipitem* toAddItem)
     93    {
     94        if(CheckifValid(toAddItem)==true)
     95        {
     96            switch(toAddItem.CheckType()){
     97                case Permanent:
     98                    Equipment.insert ( pair<std::string, ShipItem*>(toAddItem.itemname,toAddItem) );
     99                    break;
     100                case Usable:
     101                    Usable.insert ( pair<std::string, ShipItem*>(toAddItem.itemname,toAddItem) );
     102                    break;
     103                case Trunk:
     104                    Trunk.insert ( pair<std::string, ShipItem*>(toAddItem.itemname,toAddItem) );
     105                    break;
     106            }
     107        }
     108        else if(toAddItem.CheckType()==Permanent)
     109        {
     110            if(CheckifSpace()==true)
     111                Trunk.insert ( pair<std::string, ShipItem*>(toAddItem.itemname,toAddItem) );
     112        }
     113    }
     114
     115    void ShipEquipment::SwitchItem(Permanent* toSwitchItem)
     116    {
     117        multimap<string, ShipItem*>::iterator it;
     118        string equippedname;
     119        equippedname=GetNameofPermanent(toSwitchItem.CheckSubType());
     120        it=Equipment.find(equippedname);
     121        Trunk.insert (find(equippedname));
     122        Equipment.erase (it);
     123        Equipment.insert(pair<std::string, ShipItem*>(toSwitchItem.itemname,toSwitchItem)
     124    }
     125
     126    string ShipEquipment::GetNameofPermanent (subItemTypePermanent NametoGet)
     127    {
     128        multimap<string, ShipItem*>::iterator it;
     129        for ( it=Equipment.begin() ; it != Equipment.end(); it++ ){
     130            if((*it).second->CheckSubType()==NametoGet){
     131                return (*it).first.itemname;
     132            }
     133        }
     134        return 0;
     135    }
    92136}
  • code/trunk/src/orxonox/objects/pickup/ShipEquipmentClasses.h

    r2094 r2662  
    88
    99/*
    10 multimap<std::string, Item*> equipment_;
    11 equipment_.insert(pair<std::string, Item*>("Weapon", new Item()));*/
     10multimap<std::string, BaseItem*> equipment_;
     11equipment_.insert(pair<std::string, BaseItem*>("Weapon", new BaseItem()));*/
    1212
    1313
    14 /*          std::map<std::itemtype, Item*> EQClasses;
     14/*          std::map<std::itemtype, BaseItem*> EQClasses;
    1515            EQClasses["jacke"] = 0;
    16             Item* item = itemMap_["jacke"];
     16            BaseItem* item = itemMap_["jacke"];
    1717
    1818           if (itemMap_["jacke"])
     
    2323    {
    2424        public:
    25             void AddItem(Shipitem* toAddItem);
     25            /*void AddItem(Shipitem* toAddItem);
    2626            void RemoveItem(Shipitem* toRemoveItem);
    2727            bool CheckifValid(Shipitem* toBeChecked);
    2828            bool CheckifSpace();
     29            void SwitchItem(Permanent* toSwitchItem);
     30            string GetNameofPermanent (subItemTypePermanent NametoGet);*/ //holt den Namen des getragenen Items im jeweiligen Slot.
    2931
    3032        private:
    31             multimap<std::string, ShipItem*> Equipment;
    32             multimap<std::string, ShipItem*> Usable;
    33             multimap<std::string, ShipItem*> Trunk;
     33            multimap<std::string, BaseItem*> Equipment;
     34            multimap<std::string, BaseItem*> Usable;
     35            multimap<std::string, BaseItem*> Trunk;
    3436    };
    3537}
  • code/trunk/src/orxonox/objects/pickup/ShipItem.cc

    r2089 r2662  
    55    itemtype ShipItem::CheckType()
    66    {
    7         return this.type;
     7        return this->type;
    88    }
    99
    1010    subItemTypePermanent CheckSubType()
    1111    {
    12         return this.subtype_permanent;
     12        return this->subtype_permanent;
    1313    }
     14
     15    subItemTypePowerups CheckSubType()
     16    {
     17        return this->subtype_powerups;
     18    }
     19    subItemTypeUsable CheckSubType()
     20    {
     21        return this->subtype_usables;
     22    }
     23
    1424}
  • code/trunk/src/orxonox/objects/pickup/ShipItem.h

    r2094 r2662  
    2121        public:
    2222            itemType CheckType();
    23             virtual
     23            //virtual ChecksubType();
    2424
    2525        private:
     
    2727            string itemname;
    2828    };
    29 
    3029
    3130    /* Useables are Items the Player can choose when to activate and then show an instant action/effect
     
    3736            Rockets,
    3837            Repairkits,
    39             Triggers,           //trigger events usable by the player (Quests f.exp.)
     38            Triggers,       //trigger events usable by the player (Quests f.exp.)
    4039            Boosters,
    4140            Shields,
  • code/trunk/src/orxonox/objects/pickup/Usable.h

  • code/trunk/src/orxonox/objects/quest/AddQuest.cc

    r2261 r2662  
    2828
    2929/**
    30     @file AddQuest.cc
    31     @brief
    32     Implementation of the AddQuest class.
     30    @file
     31    @brief Implementation of the AddQuest class.
    3332*/
    3433
     
    4544#include "Quest.h"
    4645
    47 namespace orxonox {
    48 
     46namespace orxonox
     47{
    4948    CreateFactory(AddQuest);
    5049
     
    109108        }
    110109
    111         COUT(3) << "Quest {" << this->getQuestId() << "} successfully added to player." << std::endl;
     110        COUT(3) << "Quest {" << this->getQuestId() << "} successfully added to player: " << player << " ." << std::endl;
    112111        return true;
    113112    }
  • code/trunk/src/orxonox/objects/quest/AddQuest.h

    r2261 r2662  
    2828
    2929/**
    30     @file AddQuest.h
    31     @brief
    32     Definition of the AddQuest class.
     30    @file
     31    @brief Definition of the AddQuest class.
    3332*/
    3433
     
    4342#include "ChangeQuestStatus.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
     
    5857    {
    5958        public:
    60             AddQuest(BaseObject* creator);
    61             virtual ~AddQuest();
    62 
    63             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a AddQuest object through XML.
    64 
    65             virtual bool invoke(PlayerInfo* player); //!< Invokes the QuestEffect.
     59        AddQuest(BaseObject* creator);
     60        virtual ~AddQuest();
     61   
     62        virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a AddQuest object through XML.
     63   
     64        virtual bool invoke(PlayerInfo* player); //!< Invokes the QuestEffect.
    6665
    6766    };
  • code/trunk/src/orxonox/objects/quest/AddQuestHint.cc

    r2261 r2662  
    2828
    2929/**
    30     @file AddQuestHint.cc
    31     @brief
    32     Implementation of the AddQuestHint class.
     30    @file
     31    @brief Implementation of the AddQuestHint class.
    3332*/
    3433
     
    4443#include "QuestHint.h"
    4544
    46 namespace orxonox {
    47 
     45namespace orxonox
     46{
    4847    CreateFactory(AddQuestHint);
    4948
     
    130129        }
    131130
    132         COUT(3) << "QuestHint {" << this->getHintId() << "} successfully added to player." << std::endl;
     131        COUT(3) << "QuestHint {" << this->getHintId() << "} successfully added to player: " << player << " ." << std::endl;
    133132        return true;
    134133
  • code/trunk/src/orxonox/objects/quest/AddQuestHint.h

    r2261 r2662  
    2828
    2929/**
    30     @file AddQuestHint.h
    31     @brief
    32     Definition of the AddQuestHint class.
     30    @file
     31    @brief Definition of the AddQuestHint class.
    3332*/
    3433
     
    4241#include "QuestEffect.h"
    4342
    44 namespace orxonox {
    45 
     43namespace orxonox
     44{
    4645    /**
    4746    @brief
     
    7372            inline const std::string & getHintId(void) const
    7473                { return this->hintId_; }
     74           
    7575            bool setHintId(const std::string & id); //!< Sets the id of the QuestHint.
    7676
  • code/trunk/src/orxonox/objects/quest/AddReward.cc

    r2261 r2662  
    2828
    2929/**
    30     @file AddReward.cc
    31     @brief
    32     Implementation of the AddReward class.
     30    @file
     31    @brief Implementation of the AddReward class.
    3332*/
    3433
     
    4140#include "Rewardable.h"
    4241
    43 namespace orxonox {
    44 
     42namespace orxonox
     43{
    4544    CreateFactory(AddReward);
    4645
     
    106105    bool AddReward::invoke(PlayerInfo* player)
    107106    {
     107        COUT(3) << "AddReward on player: " << player << " ." << std::endl;
     108       
    108109        bool check = true;
    109110        for ( std::list<Rewardable*>::iterator reward = this->rewards_.begin(); reward != this->rewards_.end(); ++reward )
     
    111112            check = check && (*reward)->reward(player);
    112113        }
     114       
     115        COUT(3) << "Rewardable successfully added to player." << player << " ." << std::endl;
    113116
    114117        return check;
  • code/trunk/src/orxonox/objects/quest/AddReward.h

    r2261 r2662  
    2828
    2929/**
    30     @file AddReward.h
    31     @brief
    32     Definition of the AddReward class.
     30    @file
     31    @brief Definition of the AddReward class.
    3332*/
    3433
     
    4342#include "QuestEffect.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
     
    7877            inline void addRewardable(Rewardable* reward)
    7978                { this->rewards_.push_back(reward); }
     79       
    8080            const Rewardable* getRewardables(unsigned int index) const; //!< Returns the Rewardable object at the given index.
    8181
  • code/trunk/src/orxonox/objects/quest/CMakeLists.txt

    r2261 r2662  
    1414  QuestHint.cc
    1515  QuestItem.cc
     16  QuestListener.cc
    1617  QuestManager.cc
    1718  Rewardable.cc
  • code/trunk/src/orxonox/objects/quest/ChangeQuestStatus.cc

    r2261 r2662  
    2828
    2929/**
    30     @file ChangeQuestStatus.cc
    31     @brief
    32     Implementation of the ChangeQuestStatus class.
     30    @file
     31    @brief Implementation of the ChangeQuestStatus class.
    3332*/
    3433
     
    4039#include "QuestItem.h"
    4140
    42 namespace orxonox {
    43 
     41namespace orxonox
     42{
    4443    /**
    4544    @brief
  • code/trunk/src/orxonox/objects/quest/ChangeQuestStatus.h

    r2261 r2662  
    2828
    2929/**
    30     @file ChangeQuestStatus.h
    31     @brief
    32     Definition of the ChangeQuestStatus class.
     30    @file
     31    @brief Definition of the ChangeQuestStatus class.
    3332*/
    3433
     
    4342#include "QuestEffect.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
     
    6362        protected:
    6463            /**
    65                 @brief Returns the id of the Quest.
    66                 @return Returns the id of the Quest.
     64            @brief Returns the id of the Quest.
     65            @return Returns the id of the Quest.
    6766            */
    6867            inline const std::string & getQuestId(void) const
  • code/trunk/src/orxonox/objects/quest/CompleteQuest.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file CompleteQuest.cc
    31     @brief
    32     Implementation of the CompleteQuest class.
     30    @file
     31    @brief Implementation of the CompleteQuest class.
    3332*/
    3433
     
    4342#include "Quest.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    CreateFactory(CompleteQuest);
    4847
  • code/trunk/src/orxonox/objects/quest/CompleteQuest.h

    r2261 r2662  
    2828
    2929/**
    30     @file CompleteQuest.h
    31     @brief
    32     Definition of the CompleteQuest class.
     30    @file
     31    @brief Definition of the CompleteQuest class.
    3332*/
    3433
     
    4342#include "ChangeQuestStatus.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
  • code/trunk/src/orxonox/objects/quest/FailQuest.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file FailQuest.cc
    31     @brief
    32     Implementation of the FailQuest class.
     30    @file
     31    @brief Implementation of the FailQuest class.
    3332*/
    3433
     
    4342#include "Quest.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    CreateFactory(FailQuest);
    4847
  • code/trunk/src/orxonox/objects/quest/FailQuest.h

    r2261 r2662  
    2828
    2929/**
    30     @file FailQuest.h
    31     @brief
    32     Definition of the FailQuest class.
     30    @file
     31    @brief Definition of the FailQuest class.
    3332*/
    3433
     
    4342#include "ChangeQuestStatus.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
  • code/trunk/src/orxonox/objects/quest/GlobalQuest.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file GlobalQuest.cc
    31     @brief
    32     Implementation of the GlobalQuest class.
     30    @file
     31    @brief Implementation of the GlobalQuest class.
    3332*/
    3433
     
    3837#include "orxonox/objects/infos/PlayerInfo.h"
    3938#include "core/CoreIncludes.h"
     39#include "core/Super.h"
    4040#include "util/Exception.h"
    4141
    4242#include "QuestEffect.h"
    4343
    44 namespace orxonox {
    45 
     44namespace orxonox
     45{
    4646    CreateFactory(GlobalQuest);
    4747
     
    8888    bool GlobalQuest::fail(PlayerInfo* player)
    8989    {
    90         if(this->isFailable(player)) //!< Check whether the Quest can be failed.
    91         {
    92             this->setStatus(player, questStatus::failed);
    93            
    94             //! Iterate through all players possessing this Quest.
    95             for(std::set<PlayerInfo*>::const_iterator it = players_.begin(); it != players_.end(); it++)
    96             {
    97                 QuestEffect::invokeEffects(*it, this->getFailEffectList());
    98             }
    99 
    100             return true;
    101         }
    102        
    103         COUT(4) << "A non-completable quest was trying to be failed." << std::endl;
    104         return false;
     90        if(!this->isFailable(player)) //!< Check whether the Quest can be failed.
     91        {
     92            COUT(4) << "A non-completable quest was trying to be failed." << std::endl;
     93            return false;
     94        }
     95       
     96        Quest::fail(player);
     97   
     98    //! Iterate through all players possessing this Quest.
     99    for(std::set<PlayerInfo*>::const_iterator it = players_.begin(); it != players_.end(); it++)
     100    {
     101        QuestEffect::invokeEffects(*it, this->getFailEffectList());
     102    }
     103
     104    return true;
    105105    }
    106106
     
    117117    bool GlobalQuest::complete(PlayerInfo* player)
    118118    {
    119         if(this->isCompletable(player)) //!< Check whether the Quest can be completed.
    120         {
    121             this->setStatus(player, questStatus::completed);
    122            
    123             //! Iterate through all players possessing the Quest.
    124             for(std::set<PlayerInfo*>::const_iterator it = players_.begin(); it != players_.end(); it++)
    125             {
    126                 QuestEffect::invokeEffects(*it, this->getCompleteEffectList());
    127             }
    128            
    129             QuestEffect::invokeEffects(player, this->rewards_); //!< Invoke reward QuestEffects on the player completing the Quest.
    130             return true;
    131         }
    132        
    133         COUT(4) << "A non-completable quest was trying to be completed." << std::endl;
    134         return false;
     119        if(!this->isCompletable(player)) //!< Check whether the Quest can be completed.
     120        {
     121            COUT(4) << "A non-completable quest was trying to be completed." << std::endl;
     122            return false;
     123        }
     124       
     125        //! Iterate through all players possessing the Quest.
     126        for(std::set<PlayerInfo*>::const_iterator it = players_.begin(); it != players_.end(); it++)
     127        {
     128            QuestEffect::invokeEffects(*it, this->getCompleteEffectList());
     129        }
     130   
     131        Quest::complete(player);
     132   
     133        QuestEffect::invokeEffects(player, this->rewards_); //!< Invoke reward QuestEffects on the player completing the Quest.
     134        return true;
    135135    }
    136136
     
    207207        }
    208208
    209     return questStatus::inactive;
     209        return questStatus::inactive;
    210210    }
    211211
  • code/trunk/src/orxonox/objects/quest/GlobalQuest.h

    r2261 r2662  
    2828 
    2929/**
    30     @file GlobalQuest.h
    31     @brief
    32     Definition of the GlobalQuest class.
     30    @file
     31    @brief Definition of the GlobalQuest class.
    3332*/
    3433
     
    4443#include "Quest.h"
    4544
    46 namespace orxonox {
    47 
     45namespace orxonox
     46{
    4847    /**
    4948    @brief
     
    5655            <QuestDescription title="Title" description="Description." /> //The description of the quest.
    5756            <subquests>
    58         <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
    59         ...
    60         <Quest id="questIdn" />
    61         </subquests>
    62         <hints>
    63         <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
    64         ...
    65         <QuestHint id="hintIdn" />
    66         </hints>
     57                <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
     58                ...
     59                <Quest id="questIdn" />
     60            </subquests>
     61            <hints>
     62                <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
     63                ...
     64                <QuestHint id="hintIdn" />
     65            </hints>
    6766            <fail-effects>
    6867                <QuestEffect /> //A list of QuestEffects, invoked on all players possessing this quest, when the Quest is failed, see QuestEffect for the full XML representation.
  • code/trunk/src/orxonox/objects/quest/LocalQuest.cc

    r2261 r2662  
    2828
    2929/**
    30     @file LocalQuest.cc
    31     @brief
    32     Implementation of the LocalQuest class.
     30    @file
     31    @brief Implementation of the LocalQuest class.
    3332*/
    3433
     
    3736
    3837#include "core/CoreIncludes.h"
     38#include "core/Super.h"
    3939#include "util/Exception.h"
    4040
     
    4242#include "QuestEffect.h"
    4343
    44 namespace orxonox {
    45 
     44namespace orxonox
     45{
    4646    CreateFactory(LocalQuest);
    4747
     
    8686    bool LocalQuest::fail(PlayerInfo* player)
    8787    {
    88         if(this->isFailable(player)) //!< Checks whether the quest can be failed.
    89         {
    90             this->setStatus(player, questStatus::failed);
    91             QuestEffect::invokeEffects(player, this->getFailEffectList()); //!< Invoke the failEffects.
    92             return true;
    93         }
    94        
    95         COUT(4) << "A non-failable quest was trying to be failed." << std::endl;
    96         return false;
     88        if(!this->isFailable(player)) //!< Checks whether the quest can be failed.
     89        {
     90            COUT(4) << "A non-failable quest was trying to be failed." << std::endl;
     91            return false;
     92        }
     93       
     94        Quest::fail(player);
     95       
     96        QuestEffect::invokeEffects(player, this->getFailEffectList()); //!< Invoke the failEffects.
     97        return true;
    9798    }
    9899
     
    108109    bool LocalQuest::complete(PlayerInfo* player)
    109110    {
    110         if(this->isCompletable(player)) //!< Checks whether the Quest can be completed.
    111         {
    112             this->setStatus(player, questStatus::completed);
    113             QuestEffect::invokeEffects(player, this->getCompleteEffectList()); //!< Invoke the complete QuestEffects.
    114             return true;
    115         }
    116        
    117         COUT(4) << "A non-completable quest was trying to be completed." << std::endl;
    118         return false;
     111        if(!this->isCompletable(player)) //!< Checks whether the Quest can be completed.
     112        {
     113            COUT(4) << "A non-completable quest was trying to be completed." << std::endl;
     114            return false;
     115        }
     116       
     117        Quest::complete(player);
     118       
     119        QuestEffect::invokeEffects(player, this->getCompleteEffectList()); //!< Invoke the complete QuestEffects.
     120        return true;
    119121    }
    120122
  • code/trunk/src/orxonox/objects/quest/LocalQuest.h

    r2261 r2662  
    2828 
    2929/**
    30     @file LocalQuest.h
    31     @brief
    32     Definition of the LocalQuest class.
     30    @file
     31    @brief Definition of the LocalQuest class.
    3332*/
    3433
     
    4443#include "Quest.h"
    4544
    46 namespace orxonox {
    47 
     45namespace orxonox
     46{
    4847    /**
    4948    @brief
     
    5655            <QuestDescription title="Title" description="Description." /> //The description of the quest.
    5756            <subquests>
    58         <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
    59         ...
    60         <Quest id="questIdn" />
    61         </subquests>
    62         <hints>
    63         <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
    64         ...
    65         <QuestHint id="hintIdn" />
    66         </hints>
     57                <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
     58                ...
     59                <Quest id="questIdn" />
     60                </subquests>
     61                <hints>
     62                <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
     63                ...
     64                <QuestHint id="hintIdn" />
     65                </hints>
    6766            <fail-effects>
    6867                <QuestEffect /> //A list of QuestEffects, invoked when the Quest is failed, see QuestEffect for the full XML representation.
  • code/trunk/src/orxonox/objects/quest/Quest.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file Quest.cc
    31     @brief
    32     Implementation of the Quest class.
     30    @file
     31    @brief Implementation of the Quest class.
    3332*/
    3433
     
    4342#include "QuestHint.h"
    4443#include "QuestEffect.h"
    45 
    46 namespace orxonox {
    47 
     44#include "QuestListener.h"
     45
     46namespace orxonox
     47{
    4848    /**
    4949    @brief
     
    363363        return this->getStatus(player) == questStatus::completed;
    364364    }
     365   
     366    /**
     367    @brief
     368        Fails the Quest for an input player.
     369    @param player
     370        The player.
     371    @return
     372        Returns true if the Quest could be failed, false if not.
     373    */
     374    bool Quest::fail(PlayerInfo* player)
     375    {
     376        QuestListener::advertiseStatusChange(this->listeners_, "fail"); //!< Tells the QuestListeners, that the status has changed to failed.
     377        this->setStatus(player, questStatus::failed);
     378       
     379        COUT(4) << "Quest {" << this->getId() << "} is failed for player: " << player << " ." <<std::endl;
     380       
     381        this->getDescription()->sendFailQuestNotification();
     382        return true;
     383    }
     384   
     385    /**
     386    @brief
     387        Completes the Quest for an input player.
     388    @param player
     389        The player.
     390    @return
     391        Returns true if the Quest could be completed, false if not.
     392    */
     393    bool Quest::complete(PlayerInfo* player)
     394    {
     395        QuestListener::advertiseStatusChange(this->listeners_, "complete"); //!< Tells the QuestListeners, that the status has changed to completed.
     396        this->setStatus(player, questStatus::completed);
     397       
     398        COUT(4) << "Quest {" << this->getId() << "} is completed for player: " << player << " ." <<std::endl;
     399       
     400        this->getDescription()->sendCompleteQuestNotification();
     401        return true;
     402    }
    365403
    366404    /**
     
    374412    bool Quest::start(PlayerInfo* player)
    375413    {
    376         if(this->isStartable(player)) //!< Checks whether the quest can be started.
    377         {
    378             this->setStatus(player, questStatus::active);
    379             return true;
    380         }
    381        
    382         COUT(4) << "A non-startable quest was trying to be started." << std::endl;
    383         return false;
     414        if(!this->isStartable(player)) //!< Checks whether the quest can be started.
     415        {
     416            COUT(4) << "A non-startable quest was trying to be started." << std::endl;
     417            return false;
     418        }
     419       
     420        COUT(4) << "Quest {" << this->getId() << "} is started for player: " << player << " ." <<std::endl;
     421       
     422        QuestListener::advertiseStatusChange(this->listeners_, "start"); //!< Tells the QuestListeners, that the status has changed to active.
     423       
     424        this->setStatus(player, questStatus::active);
     425       
     426        this->getDescription()->sendAddQuestNotification();
     427        return true;
     428    }
     429   
     430    /**
     431    @brief
     432        Adds a QuestListener to the list of QuestListeners listening to this Quest.
     433    @param listener
     434        The QuestListener to be added.
     435    @return
     436        Returns true if successful, false if not.
     437    */
     438    bool Quest::addListener(QuestListener* listener)
     439    {
     440        if(listener == NULL)
     441        {
     442            COUT(2) << "A NULL-QuestListener was trying to be added to a Quests listeners." << std::endl;
     443            return false;
     444        }
     445       
     446        this->listeners_.push_back(listener);
     447        return true;
    384448    }
    385449
  • code/trunk/src/orxonox/objects/quest/Quest.h

    r2261 r2662  
    2828 
    2929/**
    30     @file Quest.h
    31     @brief
    32     Definition of the Quest class.
    33    
    34     The Quest is the parent class of LocalQuest and GlobalQuest.
     30    @file
     31    @brief Definition of the Quest class.
     32        The Quest is the parent class of LocalQuest and GlobalQuest.
    3533*/
    3634 
     
    4745#include "QuestItem.h"
    4846
    49 namespace questStatus
     47namespace orxonox
    5048{
     49    namespace questStatus
     50    {
    5151
    52     //!Different states of a Quest.
    53     enum Enum
    54     {
    55         inactive,
    56         active,
    57         failed,
    58         completed
    59     };
     52        //!Different states of a Quest.
     53        enum Enum
     54        {
     55            inactive,
     56            active,
     57            failed,
     58            completed
     59        };
    6060
    61 }
    62 
    63 namespace orxonox {
     61    }
    6462
    6563    /**
     
    9088                { return this->parentQuest_; }
    9189               
    92             /**
    93             @brief Returns the list of subquests.
    94             @return Returns a reference to the list of subquests of the quest.
    95             */
    96             inline const std::list<Quest*> & getSubQuestList(void) const
    97                 { return this->subQuests_; }
    98                    
    99             /**
    100             @brief Returns the list of all QuestHints of this Quest.
    101             @return Returns a reference to the list of QuestHints of the Quest.
    102             */
    103             inline const std::list<QuestHint*> & getHintsList(void) const
    104                 { return this->hints_; }
    105            
    106             bool isInactive(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'inactive'.
    107             bool isActive(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'active'.
    108             bool isFailed(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'failed'.
    109             bool isCompleted(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'completed'.
    110            
    111             bool start(PlayerInfo* player); //!< Sets a Quest to active.
    112             virtual bool fail(PlayerInfo* player) = 0; //!< Fails the Quest.
    113             virtual bool complete(PlayerInfo* player) = 0; //!< Completes the Quest.
     90            /**
     91            @brief Returns the list of subquests.
     92            @return Returns a reference to the list of subquests of the quest.
     93            */
     94            inline const std::list<Quest*> & getSubQuestList(void) const
     95                { return this->subQuests_; }
     96
     97            /**
     98            @brief Returns the list of all QuestHints of this Quest.
     99            @return Returns a reference to the list of QuestHints of the Quest.
     100            */
     101            inline const std::list<QuestHint*> & getHintsList(void) const
     102                { return this->hints_; }
     103       
     104            bool isInactive(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'inactive'.
     105            bool isActive(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'active'.
     106            bool isFailed(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'failed'.
     107            bool isCompleted(const PlayerInfo* player) const; //!< Returns true if the quest status for the specific player is 'completed'.
     108       
     109            bool start(PlayerInfo* player); //!< Sets a Quest to active.
     110            virtual bool fail(PlayerInfo* player); //!< Fails the Quest.
     111            virtual bool complete(PlayerInfo* player); //!< Completes the Quest.
     112       
     113            bool addListener(QuestListener* listener); //!< Adds a QuestListener to the list of QuestListeners listening to this Quest.
    114114
    115115        protected:
     
    131131                { return this->failEffects_; }
    132132               
    133             /**
    134             @brief Returns the list of complete QuestEffects.
    135             @return Returns a reference to the list of complete QuestEffects.
    136             */
    137             inline std::list<QuestEffect*> & getCompleteEffectList(void)
     133            /**
     134            @brief Returns the list of complete QuestEffects.
     135            @return Returns a reference to the list of complete QuestEffects.
     136            */
     137            inline std::list<QuestEffect*> & getCompleteEffectList(void)
    138138                { return this->completeEffects_; }
    139139
     
    141141            virtual bool setStatus(PlayerInfo* player, const questStatus::Enum & status) = 0; //!< Changes the status for a specific player.
    142142           
    143     private:
     143        private:
    144144            Quest* parentQuest_; //!< Pointer to the parentquest.
    145145            std::list<Quest*> subQuests_; //!< List of all the subquests.
     
    149149            std::list<QuestEffect*> failEffects_; //!< A list of all QuestEffects to be invoked, when the Quest has been failed.
    150150            std::list<QuestEffect*> completeEffects_; //!< A list of QuestEffects to be invoked, when the Quest has been completed.
     151           
     152            std::list<QuestListener*> listeners_; //!< A list of QuestListeners, that listen to what exactly happens with this Quest.
    151153           
    152154            bool setParentQuest(Quest* quest); //!< Sets the parentquest of the Quest.
  • code/trunk/src/orxonox/objects/quest/QuestDescription.cc

    r2261 r2662  
    2828
    2929/**
    30     @file QuestDescription.cc
    31     @brief
    32     Implementation of the QuestDescription class.
     30    @file
     31    @brief Implementation of the QuestDescription class.
    3332*/
    3433
     
    3837
    3938#include "core/CoreIncludes.h"
     39#include "orxonox/overlays/notifications/Notification.h"
    4040
    41 namespace orxonox {
    42 
     41namespace orxonox
     42{
    4343    CreateFactory(QuestDescription);
    4444
     
    7474        XMLPortParam(QuestDescription, "title", setTitle, getTitle, xmlelement, mode);
    7575        XMLPortParam(QuestDescription, "description", setDescription, getDescription, xmlelement, mode);
     76        XMLPortParam(QuestDescription, "failMessage", setFailMessage, getFailMessage, xmlelement, mode);
     77        XMLPortParam(QuestDescription, "completeMessage", setCompleteMessage, getCompleteMessage, xmlelement, mode);
    7678
    7779        COUT(3) << "New QuestDescription with title '" << this->getTitle() << "' created." << std::endl;
     80    }
     81   
     82    /**
     83    @brief
     84        This method is a helper for sending QuestDescriptions as Notifications.
     85    @param item
     86        The item the QuestDescription is for.
     87    @param status
     88        The status the QuestDescription us for.
     89    @return
     90        Returns true if successful.
     91    */
     92    bool QuestDescription::notificationHelper(const std::string & item, const std::string & status) const
     93    {
     94        std::string message = "";
     95        std::string title = "";
     96        if(item == "hint")
     97        {
     98            title = "You received a hint: '" + this->title_ + "'";
     99            message = this->description_;
     100        }
     101        else if(item == "quest")
     102        {
     103            if(status == "start")
     104            {
     105                title = "You received a new quest: '" + this->title_ + "'";
     106                message = this->description_;
     107            }
     108            else if(status == "fail")
     109            {
     110                title = "You failed the quest: '" + this->title_ + "'";
     111                message = this->failMessage_;
     112            }
     113            else if(status == "complete")
     114            {
     115                title = "You successfully completed the quest: '" + this->title_ + "'";
     116                message = this->completeMessage_;
     117            }
     118            else
     119            {
     120                COUT(2) << "Bad input in notificationHelper, this should not be happening!" << std::endl;
     121                return false;
     122            }
     123        }
     124        else
     125        {
     126            COUT(2) << "Bad input in notificationHelper, this should not be happening!" << std::endl;
     127            return false;
     128        }
     129       
     130        Notification* notification = new Notification(0, message, title, 30);
     131        notification->send();
     132        return true;
    78133    }
    79134
  • code/trunk/src/orxonox/objects/quest/QuestDescription.h

    r2261 r2662  
    2828
    2929/**
    30     @file QuestDescription.h
    31     @brief
    32     Definition of the QuestDescription class.
     30    @file
     31    @brief Definition of the QuestDescription class.
    3332*/
    3433
     
    4342#include "core/XMLPort.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
     
    5251        Creating a QuestDescription through XML goes as follows:
    5352       
    54         <QuestDescription title="Title" description="Description Text" />
     53        <QuestDescription title="Title" description="Description Text" failMessage="You fail." completeMessage="You win!" />
    5554    @author
    5655        Damian 'Mozork' Frick
    5756    */
    58     class _OrxonoxExport QuestDescription : public BaseObject {
    59 
     57    class _OrxonoxExport QuestDescription : public BaseObject
     58    {
    6059        public:
    6160            QuestDescription(BaseObject* creator);
     
    6463            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a QuestDescription object through XML.
    6564
    66         /**
    67         @brief Returns the title.
    68         @return Returns a string containing the title of the QuestDescription.
    69         */
     65            /**
     66            @brief Returns the title.
     67            @return Returns a string containing the title of the QuestDescription.
     68            */
    7069            inline const std::string & getTitle(void) const
    7170                { return this->title_; }
    7271       
    73         /**
    74         @brief Returns the description text.
    75         @return Returns a string containing the description text of the QuestDescription.
    76         */
     72            /**
     73            @brief Returns the description text.
     74            @return Returns a string containing the description text of the QuestDescription.
     75            */
    7776            inline const std::string & getDescription(void) const
    7877                { return this->description_; }
     78       
     79            /**
     80            @brief Returns the fail message.
     81            @return Returns a string containing the fail message of the QuestDescription.
     82            */
     83            inline const std::string & getFailMessage(void) const
     84                { return this->failMessage_; }
     85       
     86            /**
     87            @brief Returns the complete message.
     88            @return Returns a string containing the complete message of the QuestDescription.
     89            */
     90            inline const std::string & getCompleteMessage(void) const
     91                { return this->completeMessage_; }
     92       
     93            /**
     94            @brief Sends a Notification displaying that a QuestHint was added.
     95            @return Returns true if successful.
     96            */
     97            inline bool sendAddHintNotification(void) const
     98                { return notificationHelper("hint", ""); }
     99       
     100            /**
     101            @brief Sends a Notification displaying that a Quest was added.
     102            @return Returns true if successful.
     103            */
     104            inline bool sendAddQuestNotification(void) const
     105                { return notificationHelper("quest", "start"); }
     106       
     107            /**
     108            @brief Sends a Notification displaying that a Quest was failed.
     109            @return Returns true if successful.
     110            */
     111            inline bool sendFailQuestNotification(void) const
     112                { return notificationHelper("quest", "fail"); }
     113       
     114            /**
     115            @brief Sends a Notification displaying that a Quest was completed.
     116            @return Returns true if successful.
     117            */
     118            inline bool sendCompleteQuestNotification(void) const
     119                { return notificationHelper("quest", "complete"); }
    79120
    80121        private:
    81122            std::string title_; //!< The title.
    82123            std::string description_; //!< The description.
     124            std::string failMessage_; //!< The message displayed when the Quest is failed.
     125            std::string completeMessage_; //!< The message displayed when the Quest is completed.
     126
     127            bool notificationHelper(const std::string & item, const std::string & status) const; //!< Helper for sending QuestDescriptions as Notifications.
    83128
    84129            /**
     
    89134                { this->title_ = title; }
    90135               
    91         /**
     136            /**
    92137            @brief Sets the description text.
    93138            @param description The description text to be set.
     
    96141                { this->description_ = description; }
    97142
     143            /**
     144            @brief Sets the fail message.
     145            @param message The fail message to be set.
     146            */
     147            inline void setFailMessage(const std::string & message)
     148                { this->failMessage_ = message; }
     149               
     150            /**
     151            @brief Sets the complete message.
     152            @param message The complete message to be set.
     153            */
     154            inline void setCompleteMessage(const std::string & message)
     155                { this->completeMessage_ = message; }
     156
    98157    };
    99158
  • code/trunk/src/orxonox/objects/quest/QuestEffect.cc

    r2261 r2662  
    2828
    2929/**
    30     @file QuestEffect.cc
    31     @brief
    32     Implementation of the QuestEffect class.
     30    @file
     31    @brief Implementation of the QuestEffect class.
    3332*/
    3433
     
    4039#include "orxonox/objects/infos/PlayerInfo.h"
    4140
    42 namespace orxonox {
    43 
     41namespace orxonox
     42{
    4443    /**
    4544    @brief
     
    7170        Returns false if there was an error, view console of log for further detail.
    7271    */
    73     bool QuestEffect::invokeEffects(PlayerInfo* player, std::list<QuestEffect*> & effects)
     72    /*static*/ bool QuestEffect::invokeEffects(PlayerInfo* player, std::list<QuestEffect*> & effects)
    7473    {
    7574        bool check = true;
     75       
     76        COUT(4) << "Invoking QuestEffects on player: " << player << " ."  << std::endl;
    7677
    7778        for (std::list<QuestEffect*>::iterator effect = effects.begin(); effect != effects.end(); effect++)
  • code/trunk/src/orxonox/objects/quest/QuestEffect.h

    r2261 r2662  
    2828 
    2929/**
    30     @file QuestEffect.h
    31     @brief
    32     Definition of the QuestEffect class.
     30    @file
     31    @brief Definition of the QuestEffect class.
    3332*/
    3433
     
    4241#include "core/BaseObject.h"
    4342
    44 namespace orxonox {
    45 
     43namespace orxonox
     44{
    4645    /**
    4746    @brief
  • code/trunk/src/orxonox/objects/quest/QuestEffectBeacon.cc

    r2262 r2662  
    2828
    2929/**
    30     @file QuestEffectBeacon.cc
    31     @brief
    32     Implementation of the QuestEffectBeacon class.
     30    @file
     31    @brief Implementation of the QuestEffectBeacon class.
    3332*/
    3433
     
    4645#include "QuestEffect.h"
    4746
    48 namespace orxonox {
    49 
     47namespace orxonox
     48{
    5049    CreateFactory(QuestEffectBeacon);
    5150
     
    5453        Constructor. Registers the object and initializes defaults.
    5554    */
    56     QuestEffectBeacon::QuestEffectBeacon(BaseObject* creator) : PositionableEntity(creator)
     55    QuestEffectBeacon::QuestEffectBeacon(BaseObject* creator) : StaticEntity(creator)
    5756    {
    5857        RegisterObject(QuestEffectBeacon);
    5958       
    6059        this->status_ = QuestEffectBeaconStatus::active;
    61         this->times_ = INFINITE;
     60        this->times_ = INFINITE_TIME;
    6261    }
    6362
     
    9190        SUPER(QuestEffectBeacon, processEvent, event);
    9291   
    93     SetSubclassEvent(QuestEffectBeacon, "execute", execute, event, PlayerTrigger);
     92        SetSubclassEvent(QuestEffectBeacon, "execute", execute, event, PlayerTrigger);
    9493    }
    9594   
     
    145144            this->decrementTimes(); //!< Decrement the number of times the beacon can be used.
    146145            return true;
    147     }
    148 
    149     return false;
     146        }
     147
     148        return false;
    150149    }
    151150   
     
    187186            return false;
    188187        }
    189         if(this->getTimes() == INFINITE) //!< If times is infinity the QuestEffectBeacon can be executed an infinite number fo times.
     188        if(this->getTimes() == INFINITE_TIME) //!< If times is infinity the QuestEffectBeacon can be executed an infinite number fo times.
    190189        {
    191190            return true;
     
    193192       
    194193        this->times_ = this->times_ - 1; //!< Decrement number of times the QuestEffectBeacon can be executed.
    195     if(this->getTimes() == 0) //!< Set the QuestEffectBeacon to inactive when the number of times it can be executed is reduced to 0.
    196     {
     194        if(this->getTimes() == 0) //!< Set the QuestEffectBeacon to inactive when the number of times it can be executed is reduced to 0.
     195        {
    197196            this->status_ = QuestEffectBeaconStatus::inactive;
    198     }
     197        }
    199198       
    200199        return true;
     
    213212    bool QuestEffectBeacon::setTimes(const int & n)
    214213    {
    215         if(n < 0 && n != INFINITE)
     214        if(n < 0 && n != INFINITE_TIME)
    216215        {
    217216            return false;
  • code/trunk/src/orxonox/objects/quest/QuestEffectBeacon.h

    r2262 r2662  
    2828
    2929/**
    30     @file QuestEffectBeacon.h
    31     @brief
    32     Definition of the QuestEffectBeacon class.
     30    @file
     31    @brief Definition of the QuestEffectBeacon class.
    3332*/
    3433
     
    3837#include "OrxonoxPrereqs.h"
    3938
    40 #include "orxonox/objects/worldentities/PositionableEntity.h"
     39#include "orxonox/objects/worldentities/StaticEntity.h"
    4140
    42 namespace QuestEffectBeaconStatus
     41namespace orxonox
    4342{
     43    namespace QuestEffectBeaconStatus
     44    {
    4445
    45     //! The status of the beacon, can be either active or inactive.
    46     enum Enum
    47     {
    48         inactive,
    49         active
    50     };
     46        //! The status of the beacon, can be either active or inactive.
     47        enum Enum
     48        {
     49            inactive,
     50            active
     51        };
    5152
    52 }
    53 
    54 namespace orxonox {
     53    }
    5554
    5655    /**
     
    6160        A QuestEffectBeacon can be inactive or active.
    6261       
    63     Creating a QuestEffectBeacon through XML goes as follows:
    64    
    65     <QuestEffectBeacon times=n> //Where 'n' is eighter a number >= 0, which means the QuestEffectBeacon can be executed n times. Or n = -1, which means the QuestEffectBeacon can be executed an infinite number of times.
     62        Creating a QuestEffectBeacon through XML goes as follows:
     63       
     64        <QuestEffectBeacon times=n> //Where 'n' is eighter a number >= 0, which means the QuestEffectBeacon can be executed n times. Or n = -1, which means the QuestEffectBeacon can be executed an infinite number of times.
    6665            <effects>
    6766                <QuestEffect /> //A list of QuestEffects, invoked when the QuestEffectBeacon is executed, see QuestEffect for the full XML representation.
     
    7069            </effects>
    7170            <events>
    72         <execute>
    73             <EventListener event=eventIdString />
    74         </execute>
    75         </events>
    76         <attached>
    77            <PlayerTrigger name=eventIdString /> //A PlayerTrigger triggering the execution of the QuestEffectBeacon.
    78         </attached>
    79     </QuestEffectBeacon>
     71                <execute>
     72                    <EventListener event=eventIdString />
     73                </execute>
     74            </events>
     75            <attached>
     76                <PlayerTrigger name=eventIdString /> //A PlayerTrigger triggering the execution of the QuestEffectBeacon.
     77            </attached>
     78        </QuestEffectBeacon>
    8079    @author
    8180        Damian 'Mozork' Frick
    8281    */
    83     class _OrxonoxExport QuestEffectBeacon : public PositionableEntity
     82    class _OrxonoxExport QuestEffectBeacon : public StaticEntity
    8483    {
    85     public:
    86         QuestEffectBeacon(BaseObject* creator);
    87         virtual ~QuestEffectBeacon();
    88        
    89         virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a QuestEffectBeacon object through XML.
    90        
    91         virtual void processEvent(Event& event); //!< Processes an event for this QuestEffectBeacon.
    92        
    93         bool execute(bool b, PlayerTrigger* trigger); //!< Executes the QuestEffects of the QuestEffectBeacon.
    94        
    95         /**
    96         @brief Tests whether the QuestEffectBeacon is active.
    97         @return Returns true if the QuestEffectBeacon is active, fals if not.
    98         */
    99         inline bool isActive(void)
    100            { return this->status_ == QuestEffectBeaconStatus::active; }
    101        
    102         bool setActive(bool activate); //!< Set the status of the QuestEffectBeacon.
    103        
    104     protected:
     84        public:
     85            QuestEffectBeacon(BaseObject* creator);
     86            virtual ~QuestEffectBeacon();
     87           
     88            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a QuestEffectBeacon object through XML.
     89           
     90            virtual void processEvent(Event& event); //!< Processes an event for this QuestEffectBeacon.
     91           
     92            bool execute(bool b, PlayerTrigger* trigger); //!< Executes the QuestEffects of the QuestEffectBeacon.
     93           
     94            /**
     95            @brief Tests whether the QuestEffectBeacon is active.
     96            @return Returns true if the QuestEffectBeacon is active, fals if not.
     97            */
     98            inline bool isActive(void)
     99            { return this->status_ == QuestEffectBeaconStatus::active; }
     100           
     101            bool setActive(bool activate); //!< Set the status of the QuestEffectBeacon.
     102           
     103        protected:
    105104            bool decrementTimes(void); //!< Decrement the number of times the QuestEffectBeacon can still be executed.
    106105           
     
    111110            inline const int & getTimes(void) const
    112111                { return this->times_; }
    113 
     112   
    114113        private:
    115             static const int INFINITE = -1; //!< Constant to avoid using magic numbers.
    116        
     114            static const int INFINITE_TIME = -1; //!< Constant to avoid using magic numbers.
     115           
    117116            std::list<QuestEffect*> effects_; //!< The list of QuestEffects to be invoked on the executing player.
    118117            int times_; //!< Number of times the beacon can be exectued.
  • code/trunk/src/orxonox/objects/quest/QuestHint.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file QuestHint.cc
    31     @brief
    32     Implementation of the QuestHint class.
     30    @file
     31    @brief Implementation of the QuestHint class.
    3332*/
    3433
     
    4140#include "orxonox/objects/infos/PlayerInfo.h"
    4241#include "QuestManager.h"
     42#include "QuestDescription.h"
    4343#include "Quest.h"
    4444
    45 namespace orxonox {
    46 
     45namespace orxonox
     46{
    4747    CreateFactory(QuestHint);
    4848
     
    122122            {
    123123                this->playerStatus_[player] = questHintStatus::active;
     124               
     125                this->getDescription()->sendAddHintNotification();
    124126                return true;
    125127            }
  • code/trunk/src/orxonox/objects/quest/QuestHint.h

    r2261 r2662  
    2828 
    2929/**
    30     @file QuestHint.h
    31     @brief
    32     Definition of the QuestHint class.
     30    @file
     31    @brief Definition of the QuestHint class.
    3332*/
    3433
     
    4443#include "QuestItem.h"
    4544
    46 namespace questHintStatus
    47 {
    48 
    49     //! The status of the hint.
    50     enum Enum
    51     {
    52         inactive,
    53         active
    54     };
    55 
    56 }
    57 
    5845namespace orxonox
    5946{
     47    namespace questHintStatus
     48    {
     49
     50        //! The state of the hint.
     51        enum Enum
     52        {
     53            inactive,
     54            active
     55        };
     56
     57    }
    6058
    6159    /**
     
    9694        private:
    9795            Quest* quest_; //!< The Quest the QuestHint belongs to.
    98             std::map<const PlayerInfo*, questHintStatus::Enum> playerStatus_; //!< List of the status for each player, with the Player-pointer as key.
     96            std::map<const PlayerInfo*, questHintStatus::Enum> playerStatus_; //!< List of the states for each player, with the Player-pointer as key.
    9997
    10098    };
  • code/trunk/src/orxonox/objects/quest/QuestItem.cc

    r2261 r2662  
    2828 
    2929/**
    30     @file QuestItem.cc
    31     @brief
    32     Implementation of the QuestItem class.
     30    @file
     31    @brief Implementation of the QuestItem class.
    3332*/
    3433
     
    4039#include "QuestDescription.h"
    4140
    42 namespace orxonox {
    43 
     41namespace orxonox
     42{
    4443    /**
    4544    @brief
     
    9998    @return
    10099        Returns true if the string is likely to be of the required form.
    101     @todo
    102         Clarify form, more vigorous checks.
    103100    */
    104     bool QuestItem::isId(const std::string & id)
     101    /*static*/ bool QuestItem::isId(const std::string & id)
    105102    {
    106103        return id.size() >= 32;
  • code/trunk/src/orxonox/objects/quest/QuestItem.h

    r2261 r2662  
    2828 
    2929/**
    30     @file QuestItem.h
    31     @brief
    32     Definition of the QuestItem class.
    33    
    34     The QuestItem is the parent class of Quest and QuestHint.
     30    @file
     31    @brief Definition of the QuestItem class.
     32        The QuestItem is the parent class of Quest and QuestHint.
    3533*/
    3634
     
    4644#include "core/XMLPort.h"
    4745
    48 namespace orxonox {
    49 
    50 
     46namespace orxonox
     47{
    5148    /**
    5249    @brief
     
    6764            /**
    6865            @brief Returns the id of this QuestItem.
    69         @return Returns the id of the QuestItem.
     66            @return Returns the id of the QuestItem.
    7067            */
    7168            inline const std::string & getId(void) const
    7269                { return this->id_; }
    73         /**
    74         @brief Returns the QuestDescription of the QuestItem.
    75         @return Returns a pointer to the QuestDescription object of the QuestItem.
    76         */
     70           
     71            /**
     72            @brief Returns the QuestDescription of the QuestItem.
     73            @return Returns a pointer to the QuestDescription object of the QuestItem.
     74            */
    7775            inline const QuestDescription* getDescription(void) const
    7876                { return this->description_; }
  • code/trunk/src/orxonox/objects/quest/QuestManager.cc

    r2261 r2662  
    2828
    2929/**
    30     @file QuestManager.cc
    31     @brief
    32     Implementation of the QuestManager class.
     30    @file
     31    @brief Implementation of the QuestManager class.
    3332*/
    3433
     
    4241#include "QuestHint.h"
    4342
    44 namespace orxonox {
    45 
     43namespace orxonox
     44{
    4645    //! All Quests registered by their id's.
    4746    std::map<std::string, Quest*> QuestManager::questMap_s;
     
    7675        Returns true if successful, false if not.
    7776    */
    78     bool QuestManager::registerQuest(Quest* quest)
     77    /*static*/ bool QuestManager::registerQuest(Quest* quest)
    7978    {
    8079        if(quest == NULL) //!< Doh! Just as if there were actual quests behind NULL-pointers.
     
    108107        Returns true if successful, false if not.
    109108    */
    110     bool QuestManager::registerHint(QuestHint* hint)
     109    /*static*/ bool QuestManager::registerHint(QuestHint* hint)
    111110    {
    112111        if(hint == NULL) //!< Still not liking NULL-pointers.
     
    142141        Throws an exception if the given questId is invalid.
    143142    */
    144     Quest* QuestManager::findQuest(const std::string & questId)
     143    /*static*/ Quest* QuestManager::findQuest(const std::string & questId)
    145144    {
    146145        if(!QuestItem::isId(questId)) //!< Check vor validity of the given id.
     
    176175        Throws an exception if the given hintId is invalid.
    177176    */
    178     QuestHint* QuestManager::findHint(const std::string & hintId)
     177    /*static*/ QuestHint* QuestManager::findHint(const std::string & hintId)
    179178    {
    180179        if(!QuestItem::isId(hintId)) //!< Check vor validity of the given id.
  • code/trunk/src/orxonox/objects/quest/QuestManager.h

    r2261 r2662  
    2828
    2929/**
    30     @file QuestManager.h
    31     @brief
    32     Definition of the QuestManager class.
     30    @file
     31    @brief Definition of the QuestManager class.
    3332*/
    3433
     
    4342#include "core/BaseObject.h"
    4443
    45 namespace orxonox {
    46 
     44namespace orxonox
     45{
    4746    /**
    4847    @brief
  • code/trunk/src/orxonox/objects/quest/Rewardable.cc

    r2261 r2662  
    2828
    2929/**
    30     @file Rewardable.cc
    31     @brief
    32     Implementation of the Rewardable class.
     30    @file
     31    @brief Implementation of the Rewardable class.
    3332*/
    3433
     
    3837#include "core/CoreIncludes.h"
    3938
    40 namespace orxonox {
    41 
     39namespace orxonox
     40{
    4241    /**
    4342    @brief
  • code/trunk/src/orxonox/objects/quest/Rewardable.h

    r2261 r2662  
    2828
    2929/**
    30     @file Rewardable.h
    31     @brief
    32     Definition of the Rewardable class.
     30    @file
     31    @brief Definition of the Rewardable class.
    3332*/
    3433
     
    4039#include "core/BaseObject.h"
    4140
    42 namespace orxonox {
    43 
     41namespace orxonox
     42{
    4443    /**
    4544    @brief
     
    5251    class _OrxonoxExport Rewardable : public BaseObject
    5352    {
    54 
    5553        public:
    5654            Rewardable(BaseObject* creator);
     
    6159                Method to transcribe a rewardable object to the player.
    6260                Must be implemented by every class inheriting from Rewardable.
    63         @param player
     61            @param player
    6462                A pointer to the ControllableEntity, do whatever you want with it.
    65         @return
     63            @return
    6664                Return true if successful.
    6765            */
    68             virtual bool reward(PlayerInfo* player) = 0; //!<
     66            virtual bool reward(PlayerInfo* player) = 0;
    6967
    7068    };
  • code/trunk/src/orxonox/objects/weaponSystem/CMakeLists.txt

    r2131 r2662  
    22  Munition.cc
    33  Weapon.cc
     4  WeaponPack.cc
    45  WeaponSet.cc
    56  WeaponSlot.cc
     
    78)
    89
    9 #ADD_SOURCE_DIRECTORY(SRC_FILES munitions)
    10 #ADD_SOURCE_DIRECTORY(SRC_FILES projectiles)
    11 #ADD_SOURCE_DIRECTORY(SRC_FILES weapons)
     10ADD_SOURCE_DIRECTORY(SRC_FILES munitions)
     11ADD_SOURCE_DIRECTORY(SRC_FILES projectiles)
     12ADD_SOURCE_DIRECTORY(SRC_FILES weapons)
    1213
    1314ADD_SOURCE_FILES(SRC_FILES)
  • code/trunk/src/orxonox/objects/weaponSystem/Munition.cc

    r2097 r2662  
    3737namespace orxonox
    3838{
     39    CreateFactory(Munition);
     40
    3941    Munition::Munition(BaseObject* creator) : BaseObject(creator)
    4042    {
     
    4648    }
    4749
     50    unsigned int Munition::bullets()
     51    {
     52        if (this->bullets_ > 0)
     53            return bullets_;
     54        else
     55            return 0;
     56    }
     57
     58    unsigned int Munition::magazines()
     59    {
     60        if (this->magazines_ > 0)
     61            return magazines_;
     62        else
     63            return 0;
     64    }
     65
     66    void Munition::setMaxBullets(unsigned int amount)
     67    { this->maxBullets_ = amount; }
     68
     69    void Munition::setMaxMagazines(unsigned int amount)
     70    { this->maxMagazines_ = amount; }
     71
     72    void Munition::removeBullets(unsigned int amount)
     73    {
     74        if ( this->bullets_ != 0 )
     75            this->bullets_ = this->bullets_ - amount;
     76    }
     77
     78    void Munition::removeMagazines(unsigned int amount)
     79    {
     80        if ( this->magazines_ != 0 )
     81            this->magazines_ = this->magazines_ - amount;
     82    }
     83
     84    void Munition::addBullets(unsigned int amount)
     85    {
     86        if ( this->bullets_ == this->maxBullets_ )
     87        {
     88            //cannot add bullets to actual magazine
     89        }
     90        else
     91            this->bullets_ = this->bullets_ + amount;
     92    }
     93
     94    void Munition::addMagazines(unsigned int amount)
     95    {
     96        if ( this->magazines_ == this->maxMagazines_ )
     97        {
     98            //no more capacity for another magazine
     99        }
     100        else
     101            this->magazines_ = this->magazines_ + amount;
     102    }
     103
     104
     105    void Munition::fillBullets()
     106    {
     107//COUT(0) << "Munition::fillBullets maxBullets_=" << this->maxBullets_ << std::endl;
     108        this->bullets_ = this->maxBullets_;
     109    }
     110
     111    void Munition::fillMagazines()
     112    {
     113        this->magazines_ = this->maxMagazines_;
     114    }
     115
    48116    void Munition::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    49117    {
    50 
     118        SUPER(Munition, XMLPort, xmlelement, mode);
    51119    }
    52120
  • code/trunk/src/orxonox/objects/weaponSystem/Munition.h

    r2106 r2662  
    3434#include "core/BaseObject.h"
    3535
     36#include "Weapon.h"
     37
    3638
    3739namespace orxonox
     
    4547            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    4648
     49            void setMaxBullets(unsigned int amount);
     50            void setMaxMagazines(unsigned int amount);
     51
     52            void fillBullets();
     53            void fillMagazines();
     54
     55            unsigned int bullets();
     56            unsigned int magazines();
     57
     58            void removeBullets(unsigned int k);
     59            void removeMagazines(unsigned int k);
     60            void addBullets(unsigned int k);
     61            void addMagazines(unsigned int k);
    4762
    4863        private:
    4964
    50 
     65        protected:
     66            unsigned int bullets_;
     67            unsigned int magazines_;
     68            unsigned int maxBullets_;
     69            unsigned int maxMagazines_;
    5170    };
    5271}
  • code/trunk/src/orxonox/objects/weaponSystem/Weapon.cc

    r2098 r2662  
    3737namespace orxonox
    3838{
    39     Weapon::Weapon(BaseObject* creator) : BaseObject(creator)
     39    CreateFactory(Weapon);
     40
     41    Weapon::Weapon(BaseObject* creator) : StaticEntity(creator)
    4042    {
    4143        RegisterObject(Weapon);
     44        this->bulletReadyToShoot_ = true;
     45        this->magazineReadyToShoot_ = true;
     46        this->parentWeaponSystem_ = 0;
     47        this->attachedToWeaponSlot_ = 0;
     48        this->munition_ = 0;
     49        this->bulletLoadingTime_ = 0;
     50        this->magazineLoadingTime_ = 0;
     51        this->bReloading_ = false;
    4252
    43         this->loadingTime_ = 0;
    44         this->munition_ = 0;
    45 
     53        this->setObjectMode(0x0);
    4654    }
    4755
     
    5058    }
    5159
    52     void Weapon::addMunition()
     60
     61    void Weapon::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    5362    {
     63        SUPER(Weapon, XMLPort, xmlelement, mode);
     64        XMLPortParam(Weapon, "munitionType", setMunitionType, getMunitionType, xmlelement, mode);
     65        XMLPortParam(Weapon, "bulletLoadingTime", setBulletLoadingTime, getBulletLoadingTime, xmlelement, mode);
     66        XMLPortParam(Weapon, "magazineLoadingTime", setMagazineLoadingTime, getMagazineLoadingTime, xmlelement, mode);
     67    }
     68
     69    void Weapon::setWeapon()
     70    {
     71        this->munition_->fillBullets();
     72        this->munition_->fillMagazines();
     73    }
     74
     75
     76    void Weapon::fire()
     77    {
     78//COUT(0) << "LaserGun::fire, this=" << this << std::endl;
     79        if ( this->bulletReadyToShoot_ && this->magazineReadyToShoot_ && !this->bReloading_)
     80        {
     81//COUT(0) << "LaserGun::fire - ready to shoot" << std::endl;
     82//COUT(0) << "LaserGun::fire - bullets" << this->munition_->bullets() << std::endl;
     83            this->bulletReadyToShoot_ = false;
     84            if ( this->munition_->bullets() > 0)
     85            {
     86                //shoot
     87                this->takeBullets();
     88                this->createProjectile();
     89            }
     90            //if there are no bullets, but magazines
     91            else if ( this->munition_->magazines() > 0 && this->munition_->bullets() == 0 )
     92            {
     93//COUT(0) << "LaserGun::fire - no bullets" << std::endl;
     94                this->takeMagazines();
     95            }
     96            else
     97            {
     98//COUT(0) << "LaserGun::fire - no magazines" << std::endl;
     99                //actions
     100            }
     101        }
     102        else
     103        {
     104//COUT(0) << "LaserGun::fire - weapon not reloaded - bullets remaining:" << this->munition_->bullets() << std::endl;
     105            //actions
     106        }
    54107
    55108    }
    56109
    57     void Weapon::XMLPort(Element& xmlelement, XMLPort::Mode mode)
     110
     111    void Weapon::bulletTimer(float bulletLoadingTime)
    58112    {
    59 
     113//COUT(0) << "Weapon::bulletTimer started" << std::endl;
     114        this->bReloading_ = true;
     115        this->bulletReloadTimer_.setTimer( bulletLoadingTime , false , this , createExecutor(createFunctor(&Weapon::bulletReloaded)));
     116    }
     117    void Weapon::magazineTimer(float magazineLoadingTime)
     118    {
     119//COUT(0) << "Weapon::magazineTimer started" << std::endl;
     120        this->bReloading_ = true;
     121        this->magazineReloadTimer_.setTimer( magazineLoadingTime , false , this , createExecutor(createFunctor(&Weapon::magazineReloaded)));
    60122    }
    61123
    62     void Weapon::fire()
     124    void Weapon::bulletReloaded()
    63125    {
     126        this->bReloading_ = false;
     127        this->bulletReadyToShoot_ = true;
     128    }
    64129
     130    void Weapon::magazineReloaded()
     131    {
     132        this->bReloading_ = false;
     133        this->munition_->fillBullets();
     134        this->magazineReadyToShoot_ = true;
     135        this->bulletReadyToShoot_ = true;
    65136    }
     137
     138
     139    void Weapon::attachNeededMunition(std::string munitionName)
     140    {
     141//COUT(0) << "Weapon::attachNeededMunition, parentWeaponSystem=" << this->parentWeaponSystem_ << std::endl;
     142        //if munition type already exists attach it, else create a new one of this type and attach it to the weapon and to the WeaponSystem
     143        if (this->parentWeaponSystem_)
     144        {
     145//COUT(0) << "Weapon::attachNeededMunition " << munitionName << std::endl;
     146            Munition* munition = this->parentWeaponSystem_->getMunitionType(munitionName);
     147            if ( munition )
     148                this->munition_ = munition;
     149            else
     150            {
     151                //create new munition with identifier
     152//COUT(0) << "Weapon::attachNeededMunition, create new Munition of Type " << munitionName << std::endl;
     153                this->munitionIdentifier_ = ClassByString(munitionName);
     154                this->munition_ = this->munitionIdentifier_.fabricate(this);
     155                this->parentWeaponSystem_->setNewMunition(munitionName, this->munition_);
     156            }
     157        }
     158    }
     159
     160
     161     /*get and set functions
     162     *
     163     */
     164
     165    void Weapon::setMunitionType(std::string munitionType)
     166    {   this->munitionType_ = munitionType; }
     167
     168    const std::string Weapon::getMunitionType()
     169    {   return this->munitionType_;  }
     170
     171    void Weapon::setBulletLoadingTime(float loadingTime)
     172    {   this->bulletLoadingTime_ = loadingTime; }
     173
     174    const float Weapon::getBulletLoadingTime()
     175    {   return this->bulletLoadingTime_;  }
     176
     177    void Weapon::setMagazineLoadingTime(float loadingTime)
     178    {   this->magazineLoadingTime_ = loadingTime; }
     179
     180    const float Weapon::getMagazineLoadingTime()
     181    {   return this->magazineLoadingTime_;  }
     182
     183
     184    Munition * Weapon::getAttachedMunition(std::string munitionType)
     185    {
     186//COUT(0) << "Weapon::getAttachedMunition, parentWeaponSystem_="<< this->parentWeaponSystem_ << std::endl;
     187        this->munition_ = this->parentWeaponSystem_->getMunitionType(munitionType);
     188//COUT(0) << "Weapon::getAttachedMunition, munition_="<< this->munition_ << std::endl;
     189        return this->munition_;
     190    }
     191
     192    void Weapon::takeBullets() { };
     193    void Weapon::createProjectile() { };
     194    void Weapon::takeMagazines() { };
     195
    66196}
  • code/trunk/src/orxonox/objects/weaponSystem/Weapon.h

    r2106 r2662  
    3333
    3434#include "core/BaseObject.h"
     35#include "tools/BillboardSet.h"
     36#include "tools/Timer.h"
     37#include "core/Identifier.h"
    3538
     39#include "WeaponSystem.h"
     40#include "Munition.h"
     41
     42#include "objects/worldentities/StaticEntity.h"
    3643
    3744namespace orxonox
    3845{
    39     class _OrxonoxExport Weapon : public BaseObject
     46    class _OrxonoxExport Weapon : public StaticEntity
    4047    {
    4148        public:
     
    4552            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    4653
    47             void addMunition();
    4854            virtual void fire();
     55            void attachNeededMunition(std::string munitionType);
     56            Munition * getAttachedMunition(std::string munitiontype);
     57
     58            //reloading
     59            void bulletTimer(float bulletLoadingTime);
     60            void magazineTimer(float magazineLoadingTime);
     61            void bulletReloaded();
     62            void magazineReloaded();
     63
     64            virtual void setMunitionType(std::string munitionType);
     65            virtual const std::string getMunitionType();
     66            virtual void setBulletLoadingTime(float loadingTime);
     67            virtual const float getBulletLoadingTime();
     68            virtual void setMagazineLoadingTime(float loadingTime);
     69            virtual const float getMagazineLoadingTime();
     70
     71            virtual void takeBullets();
     72            virtual void takeMagazines();
     73            virtual void createProjectile();
     74
     75            inline void setParentWeaponSystem(WeaponSystem *parentWeaponSystem)
     76                { this->parentWeaponSystem_=parentWeaponSystem; };
     77            inline WeaponSystem * getParentWeaponSystem()
     78                { return this->parentWeaponSystem_; };
     79
     80            inline void setAttachedToWeaponSlot(WeaponSlot * wSlot)
     81                { this->attachedToWeaponSlot_ = wSlot; }
     82            inline WeaponSlot * getAttachedToWeaponSlot()
     83                { return this->attachedToWeaponSlot_; }
     84
     85            virtual void setWeapon();
    4986
    5087        private:
    51             int loadingTime_;
    52             Munition *munition_;
    5388
     89        protected:
     90            bool bReloading_;
     91            bool bulletReadyToShoot_;
     92            bool magazineReadyToShoot_;
     93            float bulletLoadingTime_;
     94            float magazineLoadingTime_;
     95            std::string munitionType_;
    5496
     97            WeaponSlot * attachedToWeaponSlot_;
     98            Munition * munition_;
     99            WeaponSystem * parentWeaponSystem_;
    55100
     101            SubclassIdentifier<Munition> munitionIdentifier_;
     102
     103            Timer<Weapon> bulletReloadTimer_;
     104            Timer<Weapon> magazineReloadTimer_;
    56105    };
    57106}
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSet.cc

    r2098 r2662  
    3333#include "core/XMLPort.h"
    3434#include "util/Debug.h"
     35#include "objects/worldentities/pawns/Pawn.h"
    3536
    3637#include "WeaponSet.h"
     38#include "WeaponPack.h"
    3739
    3840namespace orxonox
    3941{
     42    CreateFactory(WeaponSet);
     43
    4044    WeaponSet::WeaponSet(BaseObject* creator, int k) : BaseObject(creator)
    4145    {
     
    4347
    4448        this->parentWeaponSystem_ = 0;
    45 
    46         for (int i=0;i<k;i++)
    47         {
    48             attachWeaponSlot(new WeaponSlot(this));
    49         }
     49        this->attachedWeaponPack_ = 0;
    5050    }
    5151
     
    5454    }
    5555
    56     //Vorwärtsdeklaration
    57     WeaponSystem * parentWeaponSystem_;
     56    void WeaponSet::attachWeaponPack(WeaponPack *wPack)
     57    {
     58//COUT(0) << "WeaponSet::attachWeaponPack" << std::endl;
     59//COUT(0) << "........ parentWeaponSystem_=" << this->parentWeaponSystem_ << std::endl;
     60//COUT(0) << "........ this->parentWeaponSystem_->getWeaponSlotSize()" << this->parentWeaponSystem_->getWeaponSlotSize() << std::endl;
     61//COUT(0) << "........ wPack->getSize()" << wPack->getSize() << std::endl;
     62        if ( this->parentWeaponSystem_->getWeaponSlotSize()>0 && wPack->getSize()>0 && ( wPack->getSize() <= this->parentWeaponSystem_->getWeaponSlotSize() ) )
     63        {
     64//COUT(0) << "WeaponSet::attachWeaponPack after if" << std::endl;
     65            this->attachedWeaponPack_ = wPack;
     66            int wPackWeapon = 0;    //WeaponCounter for Attaching
     67            //should be possible to choose which slot to use
     68            for (  int i=0; i < wPack->getSize() ; i++  )
     69            {
     70                //at the moment this function only works for one weaponPack in the entire WeaponSystem...
     71                if ( this->parentWeaponSystem_->getWeaponSlotPointer(i)->getAttachedWeapon() == 0 && this->parentWeaponSystem_->getWeaponSlotPointer(i) != 0) //if slot not full
     72                {
     73//COUT(0) << "WeaponSet::attachWeaponPack attaching Weapon" << std::endl;
     74                    this->setWeaponSlots_.push_back( this->parentWeaponSystem_->getWeaponSlotPointer(i) );
     75                    this->parentWeaponSystem_->getWeaponSlotPointer(i)->attachWeapon( wPack->getWeaponPointer(wPackWeapon) );
     76                    this->parentWeaponSystem_->getParentPawn()->attach( wPack->getWeaponPointer(wPackWeapon) );
     77                    wPackWeapon++;
     78                }
     79                else
     80                {
     81                    for (int k=0; k < this->parentWeaponSystem_->getWeaponSlotSize(); k++)
     82                    {
     83                        if ( this->parentWeaponSystem_->getWeaponSlotPointer(k)->getAttachedWeapon() == 0 )
     84                        {
     85//COUT(0) << "WeaponSet::attachWeaponPack mode 2 k="<< k << std::endl;
     86                            this->setWeaponSlots_.push_back( this->parentWeaponSystem_->getWeaponSlotPointer(k) );
     87                            this->parentWeaponSystem_->getWeaponSlotPointer(k)->attachWeapon( wPack->getWeaponPointer(wPackWeapon) );
     88                            this->parentWeaponSystem_->getParentPawn()->attach( wPack->getWeaponPointer(wPackWeapon) );
     89                            wPackWeapon++;
     90                        }
     91                    }
     92                }
     93            }
     94        }
     95    }
    5896
    59     void WeaponSet::attachWeaponSlot(WeaponSlot *wSlot)
    60     {
    61         this->weaponSlots_.push_back(wSlot);
    62     }
    6397
    6498    void WeaponSet::fire()
    6599    {
    66         for (int i=0; i < (int) this->weaponSlots_.size(); i++)
    67         {
    68             this->weaponSlots_[i]->fire();
    69         }
     100        //fires all WeaponSlots available for this weaponSet attached from the WeaponPack
     101//COUT(0) << "WeaponSet::fire from Pack: " << this->attachedWeaponPack_ << std::endl;
     102        if (this->attachedWeaponPack_)
     103            this->attachedWeaponPack_->fire();
    70104    }
    71105
    72     WeaponSlot * WeaponSet::getWeaponSlotPointer(unsigned int n)
    73     {
    74         if (n < this->weaponSlots_.size())
    75             return this->weaponSlots_[n];
    76         else
    77             return 0;
    78     }
     106    void WeaponSet::setFireMode(const unsigned int firemode)
     107    {   this->firemode_ = firemode; }
    79108
     109    const unsigned int WeaponSet::getFireMode() const
     110    {   return this->firemode_; }
    80111
    81112    void WeaponSet::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    82113    {
    83 
     114        SUPER(WeaponSet, XMLPort, xmlelement, mode);
     115        XMLPortParam(WeaponSet, "firemode", setFireMode, getFireMode, xmlelement, mode);
    84116    }
    85117
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSet.h

    r2106 r2662  
    4848            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    4949
    50             void attachWeaponSlot(WeaponSlot *wSlot);
     50            void attachWeaponPack(WeaponPack *wPack);
    5151            void fire();
    52             WeaponSlot * getWeaponSlotPointer(unsigned int n);
     52
     53            void setFireMode(const unsigned int firemode);
     54            const unsigned int getFireMode() const;
    5355
    5456            inline void setParentWeaponSystem(WeaponSystem *parentWeaponSystem)
     
    5860
    5961        private:
    60             std::vector<WeaponSlot *> weaponSlots_;
    6162            WeaponSystem *parentWeaponSystem_;
     63            std::vector<WeaponSlot *> setWeaponSlots_;
     64            unsigned int firemode_;
     65            WeaponPack * attachedWeaponPack_;
    6266    };
    6367}
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSlot.cc

    r2098 r2662  
    3636
    3737
    38 
    3938namespace orxonox
    4039{
    41     WeaponSlot::WeaponSlot(BaseObject* creator) : BaseObject(creator)
     40    CreateFactory(WeaponSlot);
     41
     42    WeaponSlot::WeaponSlot(BaseObject* creator) : StaticEntity(creator)
    4243    {
    4344        RegisterObject(WeaponSlot);
    4445
    4546        this->unlimitedAmmo_ = false;
    46 
    4747        this->attachedWeapon_ = 0;
    48         this->parentWeaponSet_ = 0;
     48        this->setObjectMode(0x0);
    4949    }
    5050
     
    5353    }
    5454
    55     void WeaponSlot::attachWeapon(Weapon *weaponName)
    56     {
    57 
    58     }
    5955
    6056    /*sets the munition type
     
    6763    }
    6864
     65
    6966    void WeaponSlot::fire()
    7067    {
     68        if ( this->attachedWeapon_ )
     69//COUT(0) << "WeaponSlot::fire" << std::endl;
     70        this->attachedWeapon_->fire();
     71    }
    7172
    72     }
    7373
    7474    void WeaponSlot::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    7575    {
     76        SUPER(WeaponSlot, XMLPort, xmlelement, mode);
     77    }
    7678
     79    void WeaponSlot::attachWeapon(Weapon *weapon)
     80    {
     81        this->attachedWeapon_ = weapon;
     82        weapon->setAttachedToWeaponSlot(this);
     83//COUT(0) << "WeaponSlot::attachWeapon position=" << this->getWorldPosition() << std::endl;
     84        weapon->setPosition(this->getPosition());
     85    }
     86
     87    Weapon * WeaponSlot::getAttachedWeapon() const
     88    {
     89        return this->attachedWeapon_;
    7790    }
    7891}
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSlot.h

    r2106 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333
    34 #include "core/BaseObject.h"
    35 
    36 
    3734#include "Weapon.h"
    38 
     35#include "objects/worldentities/StaticEntity.h"
    3936
    4037namespace orxonox
    4138{
    42     class _OrxonoxExport WeaponSlot : public BaseObject
     39    class _OrxonoxExport WeaponSlot : public StaticEntity
    4340    {
    4441        public:
     
    4845            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    4946
    50             void attachWeapon(Weapon *weaponName);
     47            void attachWeapon(Weapon *weapon);
     48            Weapon * getAttachedWeapon() const;
    5149            void setAmmoType(bool isUnlimited);
    5250            void fire();
    5351
    54             inline void setParentWeaponSet(WeaponSet *parentWeaponSet)
    55                 { parentWeaponSet_=parentWeaponSet; }
    56             inline WeaponSet * getParentWeaponSet()
    57                 { return parentWeaponSet_; }
    58 
     52            inline void setParentWeaponSystem(WeaponSystem *parentWeaponSystem)
     53                { parentWeaponSystem_=parentWeaponSystem; }
     54            inline WeaponSystem * getParentWeaponSystem()
     55                { return parentWeaponSystem_; }
    5956
    6057
     
    6360            bool unlimitedAmmo_;
    6461
    65             WeaponSet *parentWeaponSet_;
     62            WeaponSystem *parentWeaponSystem_;
    6663    };
    6764}
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSystem.cc

    r2261 r2662  
    3737#include "WeaponSystem.h"
    3838
     39
    3940/* WEAPONSYSTEM
    4041 * creates the WeaponSystem and the ability to use weapons and munition
     
    4546namespace orxonox
    4647{
     48    CreateFactory(WeaponSystem);
     49
    4750    WeaponSystem::WeaponSystem(BaseObject* creator) : BaseObject(creator)
    4851    {
     
    5053
    5154        this->activeWeaponSet_ = 0;
    52         this->parentSpaceShip_ = 0;
     55        this->parentPawn_ = 0;
    5356    }
    5457
     
    5760    }
    5861
    59     //creates empty weaponSet
     62    void WeaponSystem::attachWeaponPack(WeaponPack *wPack, unsigned int firemode)
     63    {
     64        if (firemode < this->weaponSets_.size())
     65            this->weaponSets_[firemode]->attachWeaponPack(wPack);
     66        this->weaponPacks_.push_back(wPack);
     67    }
     68
     69    void WeaponSystem::attachWeaponSlot(WeaponSlot *wSlot)
     70    {
     71        wSlot->setParentWeaponSystem(this);
     72        this->weaponSlots_.push_back(wSlot);
     73    }
     74
    6075    void WeaponSystem::attachWeaponSet(WeaponSet *wSet)
    6176    {
     77        wSet->setParentWeaponSystem(this);
    6278        this->weaponSets_.push_back(wSet);
    63         wSet->setParentWeaponSystem(this);
    6479    }
    6580
     81    void WeaponSystem::setNewMunition(std::string munitionType, Munition * munitionToAdd)
     82    {
     83        this->munitionSet_[munitionType] = munitionToAdd;
     84    }
     85
     86    //returns the Pointer to the munitionType
     87    Munition * WeaponSystem::getMunitionType(std::string munitionType)
     88    {
     89//COUT(0) << "WeaponSystem::getMunitionType " << munitionType << std::endl;
     90        std::map<std::string, Munition *>::const_iterator it = this->munitionSet_.find(munitionType);
     91        if (it != this->munitionSet_.end())
     92            return it->second;
     93        else
     94            return 0;
     95    }
     96
     97
     98/*
    6699    //the first weaponSet is at n=0
    67100    void WeaponSystem::setActiveWeaponSet(unsigned int n)
     
    69102        if (n < this->weaponSets_.size())
    70103            this->activeWeaponSet_ = this->weaponSets_[n];
     104        else
     105            this->activeWeaponSet_ = this->weaponSets_[0];
     106    }
     107*/
     108
     109
     110    //n is the n'th weaponSet, starting with zero
     111    //SpaceShip.cc only needs to have the keybinding to a specific Set-number n
     112    void WeaponSystem::fire(WeaponMode::Enum n)
     113    {
     114        int set = 0;
     115        switch (n)
     116        {
     117            case WeaponMode::fire:
     118                set = 0;
     119                break;
     120            case WeaponMode::altFire:
     121                set = 1;
     122                break;
     123            case WeaponMode::altFire2:
     124                set = 2;
     125                break;
     126        }
     127//COUT(0) << "WeaponSystem::fire" << std::endl;
     128        if (set < (int)this->weaponSets_.size())
     129//COUT(0) << "WeaponSystem::fire - after if" << std::endl;
     130            this->weaponSets_[set]->fire();
    71131    }
    72132
    73     //n is the n'th weaponSet, starting with zero
    74     //Spaceship.cc only needs to have the keybinding to a specific Set-number n
    75     void WeaponSystem::fire(unsigned int n)
    76     {
    77         if (n < this->weaponSets_.size())
    78             this->weaponSets_[n]->fire();
    79     }
    80 
    81     void WeaponSystem::fire()
    82     {
    83         if (this->activeWeaponSet_)
    84             this->activeWeaponSet_->fire();
    85     }
    86133
    87134    WeaponSet * WeaponSystem::getWeaponSetPointer(unsigned int n)
     
    93140    }
    94141
     142    WeaponSlot * WeaponSystem::getWeaponSlotPointer(unsigned int n)
     143    {
     144        if (n < this->weaponSlots_.size())
     145            return this->weaponSlots_[n];
     146        else
     147            return 0;
     148    }
     149
     150    WeaponPack * WeaponSystem::getWeaponPackPointer(unsigned int n)
     151    {
     152        if (n < this->weaponPacks_.size())
     153            return this->weaponPacks_[n];
     154        else
     155            return 0;
     156    }
     157
    95158    void WeaponSystem::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    96159    {
    97 
     160        SUPER(WeaponSystem, XMLPort, xmlelement, mode);
    98161    }
    99162
  • code/trunk/src/orxonox/objects/weaponSystem/WeaponSystem.h

    r2261 r2662  
    3636
    3737#include "WeaponSet.h"
     38#include "WeaponPack.h"
    3839
    3940namespace orxonox
    4041{
     42
    4143    class _OrxonoxExport WeaponSystem : public BaseObject
    4244    {
     
    4749            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    4850
     51            void attachWeaponSlot(WeaponSlot *wSlot);
    4952            void attachWeaponSet(WeaponSet *wSet);
    50             void fire();
    51             void fire(unsigned int n);
    52             void setActiveWeaponSet(unsigned int n);
     53            //void fire();
     54            void fire(WeaponMode::Enum fireMode);
     55            //void setActiveWeaponSet(unsigned int n);
     56            void attachWeaponPack(WeaponPack * wPack, unsigned int firemode);
    5357            WeaponSet * getWeaponSetPointer(unsigned int n);
     58            WeaponSlot * getWeaponSlotPointer(unsigned int n);
     59            WeaponPack * getWeaponPackPointer(unsigned int n);
     60            void setNewMunition(std::string munitionType, Munition * munitionToAdd);
     61            Munition * getMunitionType(std::string munitionType);
    5462
    55             inline void setParentSpaceShip(SpaceShip *parentSpaceShip)
    56                 { parentSpaceShip_=parentSpaceShip; }
    57             inline SpaceShip * getParentSpaceShip()
    58                 { return parentSpaceShip_; }
     63            inline void setParentPawn(Pawn *parentPawn)
     64                { parentPawn_=parentPawn; }
     65            inline Pawn * getParentPawn()
     66                { return parentPawn_; }
    5967
     68            inline int getWeaponSlotSize()
     69                { return this->weaponSlots_.size(); }
    6070
    6171        private:
    6272            std::vector<WeaponSet *> weaponSets_;
     73            std::vector<WeaponSlot *> weaponSlots_;
     74            std::vector<WeaponPack *> weaponPacks_;
     75            std::map<std::string, Munition *> munitionSet_;
    6376            WeaponSet *activeWeaponSet_;
    64 
    65             SpaceShip *parentSpaceShip_;
     77            Pawn *parentPawn_;
    6678    };
    6779}
  • code/trunk/src/orxonox/objects/weaponSystem/munitions/LaserGunMunition.cc

    r2097 r2662  
    3737namespace orxonox
    3838{
    39     LaserGunMunition::LaserGunMunition(BaseObject* creator) : BaseObject(creator)
     39    CreateFactory(LaserGunMunition);
     40
     41    LaserGunMunition::LaserGunMunition(BaseObject* creator) : Munition(creator)
    4042    {
    4143        RegisterObject(LaserGunMunition);
     44
     45        this->maxBullets_ = 40;
     46        this->maxMagazines_ = 100;
    4247    }
    4348
  • code/trunk/src/orxonox/objects/weaponSystem/munitions/LaserGunMunition.h

    r2106 r2662  
    3333
    3434#include "core/BaseObject.h"
    35 
     35#include "../Munition.h"
    3636
    3737namespace orxonox
    3838{
    39     class _OrxonoxExport LaserGunMunition : public BaseObject
     39    class _OrxonoxExport LaserGunMunition : public Munition
    4040    {
    4141        public:
     
    4747
    4848        private:
    49             int bullets_;
    50             int magazines_;
    51             int maxBullets_;
    52             int maxMagazines_;
    5349
    5450
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/BillboardProjectile.cc

    r2099 r2662  
    3030#include "BillboardProjectile.h"
    3131
    32 #include <OgreBillboard.h>
     32#include <OgreBillboardSet.h>
    3333
     34#include "core/Core.h"
    3435#include "core/CoreIncludes.h"
     36#include "objects/Scene.h"
    3537
    3638namespace orxonox
     
    3840    CreateFactory(BillboardProjectile);
    3941
    40     BillboardProjectile::BillboardProjectile(BaseObject* creator, Weapon* owner) : Projectile(creator, owner)
     42    BillboardProjectile::BillboardProjectile(BaseObject* creator) : Projectile(creator)
    4143    {
    4244        RegisterObject(BillboardProjectile);
    4345
    44         this->billboard_.setBillboardSet("Examples/Flare", ColourValue(1.0, 1.0, 0.5), 1);
    45         this->attachObject(this->billboard_.getBillboardSet());
    46         this->scale(0.5);
     46        if (Core::showsGraphics())
     47        {
     48            assert(this->getScene()->getSceneManager()); // getScene() was already checked by WorldEntity
     49            this->billboard_.setBillboardSet(this->getScene()->getSceneManager(), "Examples/Flare", ColourValue(0.5, 0.5, 0.7, 0.8), 1);
     50            this->attachOgreObject(this->billboard_.getBillboardSet());
     51        }
     52
     53        this->setScale(0.2);
    4754    }
    4855
    4956    BillboardProjectile::~BillboardProjectile()
    5057    {
    51         if (this->isInitialized() && this->owner_)
    52             this->detachObject(this->billboard_.getBillboardSet());
     58        if (this->isInitialized() && Core::showsGraphics() && this->billboard_.getBillboardSet())
     59            this->detachOgreObject(this->billboard_.getBillboardSet());
    5360    }
    5461
    5562    void BillboardProjectile::setColour(const ColourValue& colour)
    5663    {
    57         this->billboard_.getBillboardSet()->getBillboard(0)->setColour(colour);
     64        this->billboard_.setColour(colour);
    5865    }
    5966
     
    6168    {
    6269        SUPER(BillboardProjectile, changedVisibility);
     70
    6371        this->billboard_.setVisible(this->isVisible());
    6472    }
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/BillboardProjectile.h

    r2099 r2662  
    4141    {
    4242        public:
    43             BillboardProjectile(BaseObject* creator, Weapon* owner = 0);
     43            BillboardProjectile(BaseObject* creator);
    4444            virtual ~BillboardProjectile();
    4545
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/ParticleProjectile.cc

    r2099 r2662  
    3030#include "ParticleProjectile.h"
    3131
    32 #include "SpaceShip.h"
     32#include <OgreParticleSystem.h>
     33#include <OgreParticleEmitter.h>
     34
     35#include "core/Core.h"
    3336#include "core/CoreIncludes.h"
    3437#include "core/ConfigValueIncludes.h"
     38#include "objects/Scene.h"
    3539
    3640namespace orxonox
     
    3842    CreateFactory(ParticleProjectile);
    3943
    40     ParticleProjectile::ParticleProjectile(BaseObject* creator, Weapon* owner) : BillboardProjectile(creator, owner)
     44    ParticleProjectile::ParticleProjectile(BaseObject* creator) : BillboardProjectile(creator)
    4145    {
    4246        RegisterObject(ParticleProjectile);
    4347
    44         this->particles_ = new ParticleInterface("Orxonox/shot2", LODParticle::normal);
    45         this->particles_->addToSceneNode(this->getNode());
    46         this->particles_->setKeepParticlesInLocalSpace(true);
    47         if (this->owner_)
     48        if (Core::showsGraphics())
    4849        {
     50            this->particles_ = new ParticleInterface(this->getScene()->getSceneManager(), "Orxonox/shot3_small", LODParticle::normal);
     51            this->attachOgreObject(this->particles_->getParticleSystem());
     52            this->particles_->setKeepParticlesInLocalSpace(0);
     53
     54            this->particles_->getAllEmitters()->setDirection(-WorldEntity::FRONT);
    4955        }
    50 //        else
    51 //        {
    52 //            this->particles_ = 0;
    53 //        }
    54 
    55         this->setConfigValues();
     56        else
     57            this->particles_ = 0;
    5658    }
    5759
     
    5961    {
    6062        if (this->isInitialized() && this->particles_)
     63        {
     64            this->detachOgreObject(this->particles_->getParticleSystem());
    6165            delete this->particles_;
    62     }
    63 
    64     void ParticleProjectile::setConfigValues()
    65     {
    66         SetConfigValue(speed_, 5000.0).description("The speed of a projectile in units per second").callback((Projectile*)this, &ParticleProjectile::speedChanged);
     66        }
    6767    }
    6868
     
    7070    {
    7171        SUPER(ParticleProjectile, changedVisibility);
    72         this->particles_->setEnabled(this->isVisible());
    73     }
    7472
    75     bool ParticleProjectile::create(){
    76       if(!Projectile::create())
    77         return false;
    78       this->particles_->getAllEmitters()->setDirection(-this->getOrientation()*Vector3(1,0,0));
    79       return true;
     73        if (this->particles_)
     74            this->particles_->setEnabled(this->isVisible());
    8075    }
    8176}
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/ParticleProjectile.h

    r2099 r2662  
    4141    {
    4242        public:
    43             ParticleProjectile(BaseObject* creator, Weapon* owner = 0);
     43            ParticleProjectile(BaseObject* creator);
    4444            virtual ~ParticleProjectile();
    4545            virtual void changedVisibility();
    46             void setConfigValues();
    47 
    48             virtual bool create();
    4946
    5047        private:
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/Projectile.cc

    r2100 r2662  
    4040#include "objects/worldentities/Model.h"
    4141#include "objects/worldentities/ParticleSpawner.h"
    42 #include "Settings.h"
     42#include "objects/collisionshapes/SphereCollisionShape.h"
     43#include "core/Core.h"
    4344
    4445namespace orxonox
    4546{
    46     float Projectile::speed_s = 5000;
    47 
    48     Projectile::Projectile(BaseObject* creator, Weapon* owner) : MovableEntity(creator), owner_(owner)
     47    Projectile::Projectile(BaseObject* creator) : MovableEntity(creator)
    4948    {
    5049        RegisterObject(Projectile);
    5150
    5251        this->setConfigValues();
    53         this->explosionTemplateName_ = "Orxonox/explosion3";
    54         this->smokeTemplateName_ = "Orxonox/smoke4";
     52        this->bDestroy_ = false;
     53        this->owner_ = 0;
    5554
    56         this->setStatic(false);
    57         this->translate(Vector3(55, 0, 0), Ogre::Node::TS_LOCAL);
     55        // Get notification about collisions
    5856
    59         if (this->owner_)
     57        if (Core::isMaster())
    6058        {
    61             this->setOrientation(this->owner_->getOrientation());
    62             this->setPosition(this->owner_->getPosition());
    63             this->setVelocity(this->owner_->getInitialDir() * this->speed_);
     59            this->enableCollisionCallback();
     60
     61            this->setCollisionType(Kinematic);
     62
     63            SphereCollisionShape* shape = new SphereCollisionShape(this);
     64            shape->setRadius(10);
     65            this->attachCollisionShape(shape);
     66
     67            this->destroyTimer_.setTimer(this->lifetime_, false, this, createExecutor(createFunctor(&Projectile::destroyObject)));
    6468        }
    65 
    66         if(!orxonox::Settings::isClient()) //only if not on client
    67           this->destroyTimer_.setTimer(this->lifetime_, false, this, createExecutor(createFunctor(&Projectile::destroyObject)));
    6869    }
    6970
     
    7677        SetConfigValue(damage_, 15.0).description("The damage caused by the projectile");
    7778        SetConfigValue(lifetime_, 4.0).description("The time in seconds a projectile stays alive");
    78         SetConfigValue(speed_, 5000.0).description("The speed of a projectile in units per second").callback(this, &Projectile::speedChanged);
    7979    }
    8080
    81     void Projectile::speedChanged()
    82     {
    83         Projectile::speed_s = this->speed_;
    84         if (this->owner_)
    85             this->setVelocity(this->owner_->getInitialDir() * this->speed_);
    86     }
    8781
    8882    void Projectile::tick(float dt)
     
    9387            return;
    9488
    95         float radius;
    96         for (ObjectList<Model>::iterator it = ObjectList<Model>::begin(); it; ++it)
    97         {
    98 //            if ((*it) != this->owner_)
    99             {
    100                 radius = it->getScale3D().x * 3.0;
    101 
    102                 if (this->getPosition().squaredDistance(it->getPosition()) <= (radius*radius))
    103                 {
    104                     // hit
    105                     ParticleSpawner* explosion = new ParticleSpawner(this->explosionTemplateName_, LODParticle::low, 2.0);
    106                     explosion->setPosition(this->getPosition());
    107                     explosion->create();
    108                     ParticleSpawner* smoke = new ParticleSpawner(this->smokeTemplateName_, LODParticle::normal, 2.0, 0.0);
    109                     smoke->setPosition(this->getPosition());
    110 //                    smoke->getParticleInterface()->setSpeedFactor(3.0);
    111                     smoke->create();
    112                     delete this;
    113                     return;
    114                 }
    115             }
    116         }
     89        if (this->bDestroy_)
     90            delete this;
    11791    }
    11892
    11993    void Projectile::destroyObject()
    12094    {
    121         delete this;
     95        if (Core::isMaster())
     96            delete this;
    12297    }
    12398
    124     bool Projectile::create(){
    125       return WorldEntity::create();
     99    bool Projectile::collidesAgainst(WorldEntity* otherObject, btManifoldPoint& contactPoint)
     100    {
     101        if (!this->bDestroy_ && Core::isMaster())
     102        {
     103            this->bDestroy_ = true;
     104
     105            if (this->owner_)
     106            {
     107                {
     108                    ParticleSpawner* effect = new ParticleSpawner(this->owner_->getCreator());
     109                    effect->setPosition(this->getPosition());
     110                    effect->setOrientation(this->getOrientation());
     111                    effect->setDestroyAfterLife(true);
     112                    effect->setSource("Orxonox/explosion3");
     113                    effect->setLifetime(2.0f);
     114                }
     115                {
     116                    ParticleSpawner* effect = new ParticleSpawner(this->owner_->getCreator());
     117                    effect->setPosition(this->getPosition());
     118                    effect->setOrientation(this->getOrientation());
     119                    effect->setDestroyAfterLife(true);
     120                    effect->setSource("Orxonox/smoke4");
     121                    effect->setLifetime(3.0f);
     122                }
     123            }
     124
     125            Pawn* victim = dynamic_cast<Pawn*>(otherObject);
     126            if (victim)
     127                victim->damage(this->damage_, this->owner_);
     128        }
     129        return false;
     130    }
     131
     132    void Projectile::destroyedPawn(Pawn* pawn)
     133    {
     134        if (this->owner_ == pawn)
     135            this->owner_ = 0;
    126136    }
    127137}
  • code/trunk/src/orxonox/objects/weaponSystem/projectiles/Projectile.h

    r2099 r2662  
    3333
    3434#include "objects/worldentities/MovableEntity.h"
     35#include "objects/worldentities/pawns/Pawn.h"
    3536#include "tools/Timer.h"
    3637
    3738namespace orxonox
    3839{
    39     class _OrxonoxExport Projectile : public MovableEntity
     40    class _OrxonoxExport Projectile : public MovableEntity, public PawnListener
    4041    {
    4142        public:
     43            Projectile(BaseObject* creator);
    4244            virtual ~Projectile();
     45
    4346            void setConfigValues();
    44             void speedChanged();
    4547            void destroyObject();
     48
    4649            virtual void tick(float dt);
     50            virtual bool collidesAgainst(WorldEntity* otherObject, btManifoldPoint& contactPoint);
     51            virtual void destroyedPawn(Pawn* pawn);
    4752
    48             virtual bool create();
    49 
    50             static float getSpeed()
    51                 { return Projectile::speed_s; }
    52 
    53         protected:
    54             Projectile(BaseObject* creator, Weapon* owner = 0);
    55             SpaceShip* owner_;
     53            inline void setOwner(Pawn* owner)
     54                { this->owner_ = owner; }
     55            inline Pawn* getOwner() const
     56                { return this->owner_; }
    5657
    5758        private:
    58             std::string explosionTemplateName_;
    59             std::string smokeTemplateName_;
    60         protected:
    61             static float speed_s;
    62             float speed_;
    63         private:
     59            Pawn* owner_;
    6460            float lifetime_;
    6561            float damage_;
     62            bool bDestroy_;
    6663            Timer<Projectile> destroyTimer_;
    6764    };
  • code/trunk/src/orxonox/objects/weaponSystem/weapons/CMakeLists.txt

    r2131 r2662  
    11SET( SRC_FILES
     2  Fusion.cc
    23  LaserGun.cc
    3   Missile.cc
     4#  Missile.cc
    45)
    56
  • code/trunk/src/orxonox/objects/weaponSystem/weapons/LaserGun.cc

    r2097 r2662  
    3434#include "util/Debug.h"
    3535
     36#include "LaserGun.h"
     37
    3638
    3739namespace orxonox
    3840{
     41    CreateFactory(LaserGun);
     42
    3943    LaserGun::LaserGun(BaseObject* creator) : Weapon(creator)
    4044    {
    4145        RegisterObject(LaserGun);
    4246
    43         projectileColor_ = ColourValue(1.0, 1.0, 0.5)
     47        this->speed_ = 1250;
     48
    4449    }
    4550
     
    4853    }
    4954
    50     LaserGun::fire()
     55    void LaserGun::takeBullets()
    5156    {
    52             BillboardProjectile* projectile = new ParticleProjectile(this);
    53             projectile->setColour(this->projectileColor_);
    54             projectile->create();
    55             if (projectile->getClassID() == 0)
    56             {
    57               COUT(3) << "generated projectile with classid 0" <<  std::endl; // TODO: remove this output
    58             }
    59 
    60             projectile->setObjectMode(0x3);
     57//COUT(0) << "LaserGun::takeBullets" << std::endl;
     58        this->munition_->removeBullets(1);
     59        this->bulletTimer(this->bulletLoadingTime_);
    6160    }
    6261
    63     LaserGun::addMunition()
     62    void LaserGun::takeMagazines()
    6463    {
    65         //this->munition_ = ;
     64        this->munition_->removeMagazines(1);
     65        this->magazineTimer(this->magazineLoadingTime_);
    6666    }
    6767
    68     void LaserGun::XMLPort(Element& xmlelement, XMLPort::Mode mode)
     68    void LaserGun::createProjectile()
    6969    {
    70 
    71     }
    72 
    73     ColorValue LaserGun::getProjectileColor()
    74     {
    75         return projectileColor_;
     70//COUT(0) << "LaserGun::createProjectile" << std::endl;
     71        BillboardProjectile* projectile = new ParticleProjectile(this);
     72        projectile->setOrientation(this->getWorldOrientation());
     73        projectile->setPosition(this->getWorldPosition());
     74        projectile->setVelocity(this->getWorldOrientation() * WorldEntity::FRONT * this->speed_);
     75        projectile->setOwner(this->getParentWeaponSystem()->getParentPawn());
    7676    }
    7777}
  • code/trunk/src/orxonox/objects/weaponSystem/weapons/LaserGun.h

    r2106 r2662  
    3434#include "core/BaseObject.h"
    3535
    36 #include "LaserGunMunition.h"
    37 #include "tools/BillboardSet.h"
     36#include "../munitions/LaserGunMunition.h"
    3837#include "util/Math.h"
     38#include "../Weapon.h"
     39#include "../projectiles/BillboardProjectile.h"
     40#include "../projectiles/ParticleProjectile.h"
    3941
    4042namespace orxonox
     
    4648            virtual ~LaserGun();
    4749
    48             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    49 
    50             ColourValue LaserGun::getProjectileColour();
     50            virtual void takeBullets();
     51            virtual void takeMagazines();
     52            virtual void createProjectile();
    5153
    5254        private:
    53             ColorValue projectileColor_;
    54 
    55 
     55            float speed_;
    5656
    5757    };
  • code/trunk/src/orxonox/objects/worldentities/Backlight.cc

    r2261 r2662  
    3030#include "Backlight.h"
    3131
    32 #include <OgreBillboard.h>
    3332#include <OgreRibbonTrail.h>
    3433#include <OgreSceneManager.h>
    3534
     35#include "core/Core.h"
    3636#include "core/CoreIncludes.h"
    37 #include "core/ConfigValueIncludes.h"
    3837#include "core/Executor.h"
    39 #include "util/Math.h"
    40 #include "GraphicsEngine.h"
     38#include "core/XMLPort.h"
     39#include "objects/Scene.h"
     40#include "util/Exception.h"
    4141
    4242namespace orxonox
     
    4444    CreateFactory(Backlight);
    4545
    46     float Backlight::timeFactor_s = 1.0;
    47 
    48     Backlight::Backlight(float maxspeed, float brakingtime, float scale)
     46    Backlight::Backlight(BaseObject* creator) : FadingBillboard(creator)
    4947    {
    5048        RegisterObject(Backlight);
    5149
    52         this->setConfigValues();
    53         this->traillength_ = 1;
    54 
    55         this->configure(maxspeed, brakingtime, scale);
    56     }
    57    
    58     bool Backlight::create(){
    59       if(!WorldEntity::create())
    60         return false;
    61      
    62       this->getNode()->setInheritScale(false);
    63 
    64       this->billboard_.setBillboardSet("Flares/backlightflare");
    65       this->attachObject(this->billboard_.getBillboardSet());
    66 
    67       this->ribbonTrail_ = GraphicsEngine::getInstance().getLevelSceneManager()->createRibbonTrail(this->getName() + "RibbonTrail");
    68       this->ribbonTrailNode_ = GraphicsEngine::getInstance().getLevelSceneManager()->getRootSceneNode()->createChildSceneNode(this->getName() + "RibbonTrailNode");
    69       this->ribbonTrailNode_->attachObject(this->ribbonTrail_);
    70       this->ribbonTrail_->addNode(this->getNode());
    71 
    72 
    73       this->ribbonTrail_->setTrailLength(this->maxTraillength_);
    74       this->ribbonTrail_->setMaterialName("Trail/backlighttrail");
    75 
    76         //this->setTimeFactor(Orxonox::getInstance().getTimeFactor());
    77       this->setTimeFactor(1.0f);
    78      
    79       this->ribbonTrail_->setMaxChainElements(this->maxTrailsegments_);
    80       this->ribbonTrail_->setTrailLength(this->traillength_ = 2 * this->maxTrailsegments_);
    81       this->ribbonTrail_->setInitialWidth(0, this->width_ * this->getScale());
    82       this->ribbonTrail_->setWidthChange(0, this->width_ * this->getScale() / this->maxLifeTime_ * Backlight::timeFactor_s);
    83       return true;
     50        this->ribbonTrail_ = 0;
     51        this->ribbonTrailNode_ = 0;
     52
     53        this->width_ = 0;
     54        this->length_ = 1.0f;
     55        this->lifetime_ = 0.001f;
     56        this->maxelements_ = 1;
     57
     58        this->tickcount_ = 0;
     59
     60        if (Core::showsGraphics())
     61        {
     62            if (!this->getScene())
     63                ThrowException(AbortLoading, "Can't create Backlight, no scene given.");
     64            if (!this->getScene()->getSceneManager())
     65                ThrowException(AbortLoading, "Can't create Backlight, no scene manager given.");
     66            if (!this->getScene()->getRootSceneNode())
     67                ThrowException(AbortLoading, "Can't create Backlight, no root scene node given.");
     68
     69            this->ribbonTrail_ = this->getScene()->getSceneManager()->createRibbonTrail(this->getNode()->getName());
     70
     71            this->ribbonTrailNode_ = this->getScene()->getRootSceneNode()->createChildSceneNode();
     72            this->ribbonTrailNode_->attachObject(this->ribbonTrail_);
     73
     74            this->ribbonTrail_->setMaxChainElements(this->maxelements_);
     75            this->ribbonTrail_->setTrailLength(this->length_);
     76            this->ribbonTrail_->setInitialWidth(0, 0);
     77        }
     78
     79        this->registerVariables();
    8480    }
    8581
     
    8884        if (this->isInitialized())
    8985        {
    90             this->detachObject(this->billboard_.getBillboardSet());
    91             GraphicsEngine::getInstance().getLevelSceneManager()->destroySceneNode(this->getName() + "RibbonTrailNode");
    92             GraphicsEngine::getInstance().getLevelSceneManager()->destroyRibbonTrail(this->ribbonTrail_);
    93         }
    94     }
    95 
    96     void Backlight::setConfigValues()
    97     {
    98         SetConfigValue(maxLifeTime_, 4.0).description("The maximal amount of seconds the trail behind a SpaceShip stays visible");
    99         SetConfigValue(trailSegmentLength_, 50).description("The length of one segment of the trail behind a SpaceShip (lower values make it more smooth)");
    100         SetConfigValue(width_, 7.0).description("The width of the trail");
    101     }
    102 
    103     void Backlight::setTimeFactor(float factor)
    104     {
    105         Backlight::timeFactor_s = factor;
    106         float change = Backlight::timeFactor_s / this->maxLifeTime_;
    107         this->ribbonTrail_->setWidthChange(0, this->width_ * change);
    108         this->updateColourChange();
    109     }
    110 
    111     void Backlight::updateColourChange()
    112     {
    113         this->ribbonTrail_->setColourChange(0, ColourValue(0, 0, 0, this->maxTraillength_ / this->traillength_ / this->maxLifeTime_ * Backlight::timeFactor_s));
    114     }
    115    
    116    
    117     void Backlight::XMLPort(Element& xmlelement, XMLPort::Mode mode){
    118       SUPER(Backlight, XMLPort, xmlelement, mode);
    119      
    120       Backlight::create();
     86            if (this->ribbonTrail_)
     87            {
     88                if (this->ribbonTrailNode_)
     89                {
     90                    this->ribbonTrailNode_->detachObject(this->ribbonTrail_);
     91                    this->getScene()->getSceneManager()->destroySceneNode(this->ribbonTrailNode_->getName());
     92                }
     93                this->getScene()->getSceneManager()->destroyRibbonTrail(this->ribbonTrail_);
     94            }
     95        }
     96    }
     97
     98    void Backlight::XMLPort(Element& xmlelement, XMLPort::Mode mode)
     99    {
     100        SUPER(Backlight, XMLPort, xmlelement, mode);
     101
     102        XMLPortParam(Backlight, "length",        setLength,        getLength,        xmlelement, mode).defaultValues(100.0f);
     103        XMLPortParam(Backlight, "width",         setWidth,         getWidth,         xmlelement, mode).defaultValues(1.0f);
     104        XMLPortParam(Backlight, "elements",      setMaxElements,   getMaxElements,   xmlelement, mode).defaultValues(10);
     105        XMLPortParam(Backlight, "lifetime",      setLifetime,      getLifetime,      xmlelement, mode).defaultValues(1.0f);
     106        XMLPortParam(Backlight, "trailmaterial", setTrailMaterial, getTrailMaterial, xmlelement, mode);
     107    }
     108
     109    void Backlight::registerVariables()
     110    {
     111        registerVariable(this->width_,         variableDirection::toclient, new NetworkCallback<Backlight>(this, &Backlight::update_width));
     112        registerVariable(this->lifetime_,      variableDirection::toclient, new NetworkCallback<Backlight>(this, &Backlight::update_lifetime));
     113        registerVariable(this->length_,        variableDirection::toclient, new NetworkCallback<Backlight>(this, &Backlight::update_length));
     114        registerVariable(this->maxelements_,   variableDirection::toclient, new NetworkCallback<Backlight>(this, &Backlight::update_maxelements));
     115        registerVariable(this->trailmaterial_, variableDirection::toclient, new NetworkCallback<Backlight>(this, &Backlight::update_trailmaterial));
     116    }
     117
     118    void Backlight::changedColour()
     119    {
     120        FadingBillboard::changedColour();
     121
     122        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     123            this->ribbonTrail_->setInitialColour(0, this->getFadedColour());
     124    }
     125
     126    void Backlight::update_width()
     127    {
     128        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     129            this->ribbonTrail_->setInitialWidth(0, this->width_ * this->getWorldScale());
     130        this->update_lifetime();
     131    }
     132
     133    void Backlight::update_lifetime()
     134    {
     135        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     136        {
     137            this->ribbonTrail_->setWidthChange(0, this->width_ * this->getWorldScale() / this->lifetime_ * this->getTimeFactor());
     138            this->ribbonTrail_->setColourChange(0, 0, 0, 0, 1.0f / this->lifetime_ * this->getTimeFactor());
     139        }
     140    }
     141
     142    void Backlight::update_length()
     143    {
     144        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     145            this->ribbonTrail_->setTrailLength(this->length_ * this->getWorldScale());
     146    }
     147
     148    void Backlight::update_maxelements()
     149    {
     150        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     151            this->ribbonTrail_->setMaxChainElements(this->maxelements_);
     152    }
     153
     154    void Backlight::update_trailmaterial()
     155    {
     156        if (this->ribbonTrail_ && this->tickcount_ >= 2)
     157            this->ribbonTrail_->setMaterialName(this->trailmaterial_);
     158    }
     159
     160    void Backlight::changedVisibility()
     161    {
     162        SUPER(Backlight, changedVisibility);
     163
     164        if (this->ribbonTrail_)
     165            this->ribbonTrail_->setVisible(this->isVisible());
     166    }
     167
     168    void Backlight::startturnonoff()
     169    {
     170        FadingBillboard::startturnonoff();
     171
     172        if (this->ribbonTrail_ && this->isActive() && this->isVisible())
     173            this->ribbonTrail_->setVisible(true);
     174    }
     175
     176    void Backlight::stopturnonoff()
     177    {
     178        this->postprocessingtime_ = max(0.0f, this->lifetime_ - this->turnofftime_);
     179
     180        FadingBillboard::stopturnonoff();
     181
     182        if (this->ribbonTrail_)
     183            this->ribbonTrail_->setInitialColour(0, this->getFadedColour());
     184    }
     185
     186    void Backlight::poststopturnonoff()
     187    {
     188        FadingBillboard::poststopturnonoff();
     189
     190        if (this->ribbonTrail_)
     191            this->ribbonTrail_->setVisible(false);
     192    }
     193
     194    void Backlight::changedScale()
     195    {
     196        SUPER(Backlight, changedScale);
     197
     198        this->update_width();
     199        this->update_length();
    121200    }
    122201
    123202    void Backlight::tick(float dt)
    124203    {
     204        if (this->tickcount_ < 2)
     205        {
     206            ++this->tickcount_;
     207            if (this->tickcount_ == 2)
     208            {
     209                this->changedColour();
     210                this->update_width();
     211                this->update_lifetime();
     212                this->update_length();
     213                this->update_maxelements();
     214                this->update_trailmaterial();
     215                if (this->ribbonTrail_)
     216                    this->ribbonTrail_->addNode(this->node_);
     217            }
     218        }
     219
    125220        SUPER(Backlight, tick, dt);
    126221
    127         if (this->isActive())
    128         {
    129             if (this->traillength_ < this->maxTraillength_)
    130             {
    131                 this->traillength_ = min<float>(this->maxTraillength_, this->traillength_ + dt * this->maxTraillength_ / this->maxLifeTime_);
    132                 this->updateColourChange();
    133             }
    134         }
    135         else
    136         {
    137             if (this->traillength_ > 1)
    138             {
    139                 this->traillength_ = max<float>(1, this->traillength_ - this->brakefactor_ * dt * this->maxTraillength_ / this->maxLifeTime_);
    140                 this->updateColourChange();
    141             }
    142         }
    143 
    144         this->ribbonTrail_->setTrailLength(this->traillength_);
    145     }
    146 
    147     void Backlight::setColour(const ColourValue& colour)
    148     {
    149         this->billboard_.getBillboardSet()->getBillboard(0)->setColour(colour);
    150         this->ribbonTrail_->setInitialColour(0, ColourValue(colour.r / 4 + 0.75, colour.g / 4 + 0.75, colour.b / 4 + 0.75));
    151     }
    152 
    153     void Backlight::configure(float maxspeed, float brakingtime, float scale)
    154     {
    155         this->maxTraillength_ = this->maxLifeTime_ * maxspeed;
    156         this->maxTrailsegments_ = (size_t)(this->maxTraillength_ / this->trailSegmentLength_);
    157 
    158         this->brakefactor_ = this->maxLifeTime_ / brakingtime;
    159 
    160         this->scale(scale);
    161     }
    162 
    163     void Backlight::changedVisibility()
    164     {
    165         SUPER(Backlight, changedVisibility);
    166 
    167         this->billboard_.setVisible(this->isVisible());
    168         this->ribbonTrail_->setVisible(this->isVisible());
     222        if (this->ribbonTrail_ && this->changedirection_ != 0)
     223        {
     224            // we use alpha_blend, only adjust alpha
     225            const ColourValue& colour = this->getColour();
     226            this->ribbonTrail_->setInitialColour(0, colour.r, colour.g, colour.b, this->getFadedColour().a);
     227        }
     228    }
     229
     230    void Backlight::changedTimeFactor(float factor_new, float factor_old)
     231    {
     232        this->update_lifetime();
    169233    }
    170234}
  • code/trunk/src/orxonox/objects/worldentities/Backlight.h

    r2261 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 
    34 #include "PositionableEntity.h"
    35 #include "tools/BillboardSet.h"
     33#include "FadingBillboard.h"
     34#include "gamestates/GSRoot.h"
    3635
    3736namespace orxonox
    3837{
    39     class _OrxonoxExport Backlight : public PositionableEntity
     38    class _OrxonoxExport Backlight : public FadingBillboard, public TimeFactorListener
    4039    {
    4140        public:
    42             Backlight(float maxspeed = 1.0, float brakingtime = 1.0, float scale = 1.0);
     41            Backlight(BaseObject* creator);
    4342            virtual ~Backlight();
    4443
    45             void setConfigValues();
    4644            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
     45            void registerVariables();
     46
    4747            virtual void tick(float dt);
    4848            virtual void changedVisibility();
    49             virtual bool create();
    5049
    51             void setColour(const ColourValue& colour);
    52             void setTimeFactor(float factor);
     50            inline void setWidth(float width)
     51                { this->width_ = width; this->update_width(); }
     52            inline float getWidth() const
     53                { return this->width_; }
     54
     55            inline void setLifetime(float lifetime)
     56                { this->lifetime_ = lifetime; this->update_lifetime(); }
     57            inline float getLifetime() const
     58                { return this->lifetime_; }
     59
     60            inline void setLength(float length)
     61                { this->length_ = length; this->update_length(); }
     62            inline float getLength() const
     63                { return this->length_; }
     64
     65            inline void setMaxElements(size_t maxelements)
     66                { this->maxelements_ = maxelements; this->update_maxelements(); }
     67            inline size_t getMaxElements() const
     68                { return this->maxelements_; }
     69
     70            inline void setTrailMaterial(const std::string& material)
     71                { this->trailmaterial_ = material; this->update_trailmaterial(); }
     72            inline const std::string& getTrailMaterial() const
     73                { return this->trailmaterial_; }
     74
     75            virtual void changedScale();
     76
     77        protected:
     78            virtual void changedTimeFactor(float factor_new, float factor_old);
    5379
    5480        private:
    55             void configure(float maxspeed, float brakingtime, float scale = 1);
    56             void updateColourChange();
     81            virtual void startturnonoff();
     82            virtual void stopturnonoff();
     83            virtual void poststopturnonoff();
     84            virtual void changedColour();
     85            void update_width();
     86            void update_lifetime();
     87            void update_length();
     88            void update_maxelements();
     89            void update_trailmaterial();
    5790
    58             static float timeFactor_s;
    59             BillboardSet billboard_;
     91            Ogre::RibbonTrail* ribbonTrail_;
    6092            Ogre::SceneNode* ribbonTrailNode_;
    61             Ogre::RibbonTrail* ribbonTrail_;
    62 
    63             float maxLifeTime_;
    64             float trailSegmentLength_;
    6593            float width_;
    66 
    67             float brakefactor_;
    68 
    69             float maxTraillength_;
    70             float traillength_;
    71 
    72             size_t maxTrailsegments_;
     94            float length_;
     95            float lifetime_;
     96            size_t maxelements_;
     97            std::string trailmaterial_;
     98            char tickcount_;
    7399    };
    74100}
  • code/trunk/src/orxonox/objects/worldentities/Billboard.cc

    r2171 r2662  
    3030#include "Billboard.h"
    3131
     32#include <OgreBillboardSet.h>
     33
    3234#include "core/CoreIncludes.h"
    3335#include "core/XMLPort.h"
     36#include "core/Core.h"
    3437#include "objects/Scene.h"
    3538
     
    3841    CreateFactory(Billboard);
    3942
    40     Billboard::Billboard(BaseObject* creator) : PositionableEntity(creator)
     43    Billboard::Billboard(BaseObject* creator) : StaticEntity(creator)
    4144    {
    4245        RegisterObject(Billboard);
     46
     47        this->material_ = "";
     48        this->colour_ = ColourValue::White;
    4349
    4450        this->registerVariables();
     
    5056        {
    5157            if (this->isInitialized() && this->billboard_.getBillboardSet())
    52                 this->getNode()->detachObject(this->billboard_.getName());
     58                this->detachOgreObject(this->billboard_.getBillboardSet());
    5359        }
    5460    }
     
    6470    void Billboard::registerVariables()
    6571    {
    66         REGISTERSTRING(this->material_, direction::toclient, new NetworkCallback<Billboard>(this, &Billboard::changedMaterial));
    67         REGISTERDATA  (this->colour_,   direction::toclient, new NetworkCallback<Billboard>(this, &Billboard::changedColour));
     72        registerVariable(this->material_, variableDirection::toclient, new NetworkCallback<Billboard>(this, &Billboard::changedMaterial));
     73        registerVariable(this->colour_,   variableDirection::toclient, new NetworkCallback<Billboard>(this, &Billboard::changedColour));
    6874    }
    6975
    7076    void Billboard::changedMaterial()
    7177    {
     78        if (this->material_ == "")
     79            return;
     80
    7281        if (!this->billboard_.getBillboardSet())
    7382        {
    74             if (this->getScene() && this->getScene()->getSceneManager())
     83            if (this->getScene() && Core::showsGraphics())
    7584            {
    7685                this->billboard_.setBillboardSet(this->getScene()->getSceneManager(), this->material_, this->colour_, 1);
    7786                if (this->billboard_.getBillboardSet())
    78                     this->getNode()->attachObject(this->billboard_.getBillboardSet());
     87                     this->attachOgreObject(this->billboard_.getBillboardSet());
    7988                this->billboard_.setVisible(this->isVisible());
    8089            }
     
    8897        if (!this->billboard_.getBillboardSet())
    8998        {
    90             if (this->getScene() && this->getScene()->getSceneManager())
     99/*
     100            if (this->getScene() && Core::showsGraphics() && (this->material_ != ""))
    91101            {
    92102                this->billboard_.setBillboardSet(this->getScene()->getSceneManager(), this->material_, this->colour_, 1);
    93103                if (this->billboard_.getBillboardSet())
    94                     this->getNode()->attachObject(this->billboard_.getBillboardSet());
     104                    this->attachOgreObject(this->billboard_.getBillboardSet());
    95105                this->billboard_.setVisible(this->isVisible());
    96106            }
     107*/
    97108        }
    98109        else
  • code/trunk/src/orxonox/objects/worldentities/Billboard.h

    r2087 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 #include "PositionableEntity.h"
     33#include "StaticEntity.h"
    3434#include "util/Math.h"
    3535#include "tools/BillboardSet.h"
     
    3737namespace orxonox
    3838{
    39     class _OrxonoxExport Billboard : public PositionableEntity
     39    class _OrxonoxExport Billboard : public StaticEntity
    4040    {
    4141        public:
     
    6161                { return this->colour_; }
    6262
     63        protected:
     64            inline BillboardSet& getBillboardSet()
     65                { return this->billboard_; }
     66
     67            virtual void changedColour();
     68
    6369        private:
    6470            void changedMaterial();
    65             void changedColour();
    6671
    6772            BillboardSet billboard_;
  • code/trunk/src/orxonox/objects/worldentities/BlinkingBillboard.cc

    r2171 r2662  
    6868    void BlinkingBillboard::registerVariables()
    6969    {
    70 //        REGISTERDATA(this->amplitude_, direction::toclient);
    71 //        REGISTERDATA(this->frequency_, direction::toclient);
    72 //        REGISTERDATA(this->phase_,     direction::toclient);
     70//        registerVariable(this->amplitude_, variableDirection::toclient);
     71//        registerVariable(this->frequency_, variableDirection::toclient);
     72//        registerVariable(this->phase_,     variableDirection::toclient);
    7373    }
    7474
    7575    void BlinkingBillboard::tick(float dt)
    7676    {
     77        SUPER(BlinkingBillboard, tick, dt);
     78
    7779        if (Core::isMaster() && this->isActive())
    7880        {
  • code/trunk/src/orxonox/objects/worldentities/CMakeLists.txt

    r2131 r2662  
    11SET( SRC_FILES
    22  WorldEntity.cc
    3   PositionableEntity.cc
     3  StaticEntity.cc
    44  MovableEntity.cc
     5  MobileEntity.cc
    56  ControllableEntity.cc
    6   Model.cc
     7
     8  Backlight.cc
    79  Billboard.cc
    810  BlinkingBillboard.cc
     11  ExplosionChunk.cc
     12  FadingBillboard.cc
    913  Light.cc
    1014  Camera.cc
    1115  CameraPosition.cc
    12   SpawnPoint.cc
     16  Model.cc
    1317  ParticleEmitter.cc
    1418  ParticleSpawner.cc
    15 #  Backlight.cc
     19  Planet.cc
     20  SpawnPoint.cc
    1621)
    1722
  • code/trunk/src/orxonox/objects/worldentities/Camera.cc

    r2261 r2662  
    3636#include <OgreSceneManager.h>
    3737#include <OgreSceneNode.h>
    38 #include <OgreViewport.h>
    3938
    4039#include "util/Exception.h"
     
    4847    CreateFactory(Camera);
    4948
    50     Camera::Camera(BaseObject* creator) : PositionableEntity(creator)
     49    Camera::Camera(BaseObject* creator) : StaticEntity(creator)
    5150    {
    5251        RegisterObject(Camera);
    5352
    54         if (!this->getScene() || !this->getScene()->getSceneManager())
    55             ThrowException(AbortLoading, "Can't create Camera, no scene or no scene manager given.");
     53        if (!this->getScene())
     54            ThrowException(AbortLoading, "Can't create Camera, no scene.");
     55        if (!this->getScene()->getSceneManager())
     56            ThrowException(AbortLoading, "Can't create Camera, no scene-manager given.");
     57        if (!this->getScene()->getRootSceneNode())
     58            ThrowException(AbortLoading, "Can't create Camera, no root-scene-node given.");
    5659
    5760        this->camera_ = this->getScene()->getSceneManager()->createCamera(getUniqueNumberString());
    58         this->getNode()->attachObject(this->camera_);
     61        this->cameraNode_ = this->getScene()->getRootSceneNode()->createChildSceneNode();
     62        this->attachNode(this->cameraNode_);
     63        this->cameraNode_->attachObject(this->camera_);
    5964
    6065        this->bHasFocus_ = false;
     
    6671        this->setConfigValues();
    6772        this->configvaluecallback_changedNearClipDistance();
    68 
    69         this->requestFocus(); // ! HACK ! REMOVE THIS !
    7073    }
    7174
     
    7578        {
    7679            this->releaseFocus();
     80
     81            this->cameraNode_->detachAllObjects();
     82            this->getScene()->getSceneManager()->destroyCamera(this->camera_);
     83
     84            if (this->bDrag_)
     85                this->detachNode(this->cameraNode_);
     86
     87            if (this->getScene()->getSceneManager())
     88                this->getScene()->getSceneManager()->destroySceneNode(this->cameraNode_->getName());
    7789        }
    7890    }
     
    90102    void Camera::tick(float dt)
    91103    {
    92 /*
    93         // this stuff here may need some adjustments
    94         float coeff = (this->bDrag_) ? min(1.0f, 15.0f * dt) : (1.0f);
     104        SUPER(Camera, tick, dt);
    95105
    96         Vector3 offset = this->getNode()->getWorldPosition() - this->cameraNode_->getWorldPosition();
    97         this->cameraNode_->translate(coeff * offset);
     106        if (this->bDrag_)
     107        {
     108            // this stuff here may need some adjustments
     109            float coeff = min(1.0f, 15.0f * dt);
    98110
    99         this->cameraNode_->setOrientation(Quaternion::Slerp(coeff, this->cameraNode_->getWorldOrientation(), this->getWorldOrientation(), false));
    100 */
     111            Vector3 offset = this->getWorldPosition() - this->cameraNode_->getWorldPosition();
     112            this->cameraNode_->translate(coeff * offset);
     113
     114            this->cameraNode_->setOrientation(Quaternion::Slerp(coeff, this->cameraNode_->getWorldOrientation(), this->getWorldOrientation(), true));
     115            //this->cameraNode_->setOrientation(this->getWorldOrientation());
     116        }
    101117    }
    102118
     
    120136    }
    121137
    122     void Camera::setFocus(Ogre::Viewport* viewport)
     138    void Camera::setFocus()
    123139    {
    124140        this->bHasFocus_ = true;
    125         viewport->setCamera(this->camera_);
     141        CameraManager::getInstance().useCamera(this->camera_);
     142    }
     143
     144    void Camera::setDrag(bool bDrag)
     145    {
     146        if (bDrag != this->bDrag_)
     147        {
     148            this->bDrag_ = bDrag;
     149
     150            if (!bDrag)
     151            {
     152                this->attachNode(this->cameraNode_);
     153                this->cameraNode_->setPosition(Vector3::ZERO);
     154                this->cameraNode_->setOrientation(Quaternion::IDENTITY);
     155            }
     156            else
     157            {
     158                this->detachNode(this->cameraNode_);
     159                this->cameraNode_->setPosition(this->getWorldPosition());
     160                this->cameraNode_->setOrientation(this->getWorldOrientation());
     161            }
     162        }
    126163    }
    127164}
  • code/trunk/src/orxonox/objects/worldentities/Camera.h

    r2261 r2662  
    3333
    3434#include <OgrePrerequisites.h>
    35 #include "objects/worldentities/PositionableEntity.h"
     35#include "objects/worldentities/StaticEntity.h"
    3636#include "objects/Tickable.h"
    3737
    3838namespace orxonox
    3939{
    40     class _OrxonoxExport Camera : public PositionableEntity, public Tickable
     40    class _OrxonoxExport Camera : public StaticEntity, public Tickable
    4141    {
    4242        friend class CameraManager;
     
    5555                { return this->bHasFocus_; }
    5656
    57             inline void setDrag(bool bDrag)
    58                 { this->bDrag_ = bDrag; }
     57            void setDrag(bool bDrag);
    5958            inline bool getDrag() const
    6059                { return this->bDrag_; }
     
    6261        private:
    6362            void removeFocus();
    64             void setFocus(Ogre::Viewport* viewport);
     63            void setFocus();
    6564            void configvaluecallback_changedNearClipDistance();
    6665
    67             Ogre::Camera*   camera_;
    68             float           nearClipDistance_;
    69             bool            bHasFocus_;
    70             bool            bDrag_;
     66            Ogre::Camera*    camera_;
     67            Ogre::SceneNode* cameraNode_;
     68            float            nearClipDistance_;
     69            bool             bHasFocus_;
     70            bool             bDrag_;
    7171    };
    7272}
  • code/trunk/src/orxonox/objects/worldentities/CameraPosition.cc

    r2087 r2662  
    3838    CreateFactory(CameraPosition);
    3939
    40     CameraPosition::CameraPosition(BaseObject* creator) : PositionableEntity(creator)
     40    CameraPosition::CameraPosition(BaseObject* creator) : StaticEntity(creator)
    4141    {
    4242        RegisterObject(CameraPosition);
    4343
    4444        this->bDrag_ = false;
     45        this->bAllowMouseLook_ = false;
    4546
    4647        this->setObjectMode(0x0);
     
    5657
    5758        XMLPortParam(CameraPosition, "drag", setDrag, getDrag, xmlelement, mode).defaultValues(false);
     59        XMLPortParam(CameraPosition, "mouselook", setAllowMouseLook, getAllowMouseLook, xmlelement, mode).defaultValues(false);
    5860    }
    5961
    6062    void CameraPosition::attachCamera(Camera* camera)
    6163    {
    62         camera->setDrag(this->bDrag_);
     64        if (!this->bDrag_)
     65            camera->setDrag(false);
     66
    6367        this->attach(camera);
     68
     69        if (this->bDrag_)
     70            camera->setDrag(true);
    6471    }
    6572}
  • code/trunk/src/orxonox/objects/worldentities/CameraPosition.h

    r2087 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333
    34 #include "objects/worldentities/PositionableEntity.h"
     34#include "objects/worldentities/StaticEntity.h"
    3535
    3636namespace orxonox
    3737{
    38     class _OrxonoxExport CameraPosition : public PositionableEntity
     38    class _OrxonoxExport CameraPosition : public StaticEntity
    3939    {
    4040        public:
     
    4949                { return this->bDrag_; }
    5050
     51            inline void setAllowMouseLook(bool bAllow)
     52                { this->bAllowMouseLook_ = bAllow; }
     53            inline bool getAllowMouseLook() const
     54                { return this->bAllowMouseLook_; }
     55
    5156            void attachCamera(Camera* camera);
    5257
    5358        private:
    5459            bool bDrag_;
     60            bool bAllowMouseLook_;
    5561    };
    5662}
  • code/trunk/src/orxonox/objects/worldentities/ControllableEntity.cc

    r2171 r2662  
    2323 *      Fabian 'x3n' Landau
    2424 *   Co-authors:
    25  *      ...
     25 *      Reto Grieder
    2626 *
    2727 */
     
    3030#include "ControllableEntity.h"
    3131
     32#include <OgreSceneManager.h>
     33
    3234#include "core/CoreIncludes.h"
     35#include "core/ConfigValueIncludes.h"
    3336#include "core/Core.h"
    3437#include "core/XMLPort.h"
    3538#include "core/Template.h"
    3639
     40#include "objects/Scene.h"
    3741#include "objects/infos/PlayerInfo.h"
    3842#include "objects/worldentities/Camera.h"
    3943#include "objects/worldentities/CameraPosition.h"
     44#include "objects/gametypes/Gametype.h"
    4045#include "overlays/OverlayGroup.h"
    4146
     
    4449    CreateFactory(ControllableEntity);
    4550
    46     ControllableEntity::ControllableEntity(BaseObject* creator) : WorldEntity(creator)
     51    ControllableEntity::ControllableEntity(BaseObject* creator) : MobileEntity(creator)
    4752    {
    4853        RegisterObject(ControllableEntity);
    4954
    50         this->bControlled_ = false;
     55        this->bHasLocalController_ = false;
     56        this->bHasHumanController_ = false;
     57
    5158        this->server_overwrite_ = 0;
    5259        this->client_overwrite_ = 0;
     
    5663        this->camera_ = 0;
    5764        this->bDestroyWhenPlayerLeft_ = false;
    58 
    59         this->velocity_ = Vector3::ZERO;
    60         this->acceleration_ = Vector3::ZERO;
    61 
    62         this->server_position_ = Vector3::ZERO;
    63         this->client_position_ = Vector3::ZERO;
    64         this->server_velocity_ = Vector3::ZERO;
    65         this->client_velocity_ = Vector3::ZERO;
    66         this->server_orientation_ = Quaternion::IDENTITY;
    67         this->client_orientation_ = Quaternion::IDENTITY;
    68 
     65        this->cameraPositionRootNode_ = this->node_->createChildSceneNode();
     66        this->bMouseLook_ = false;
     67        this->mouseLookSpeed_ = 200;
     68
     69        this->gtinfo_ = 0;
     70        this->gtinfoID_ = OBJECTID_UNKNOWN;
     71        this->changedGametype();
     72
     73        this->server_position_         = Vector3::ZERO;
     74        this->client_position_         = Vector3::ZERO;
     75        this->server_linear_velocity_  = Vector3::ZERO;
     76        this->client_linear_velocity_  = Vector3::ZERO;
     77        this->server_orientation_      = Quaternion::IDENTITY;
     78        this->client_orientation_      = Quaternion::IDENTITY;
     79        this->server_angular_velocity_ = Vector3::ZERO;
     80        this->client_angular_velocity_ = Vector3::ZERO;
     81
     82
     83        this->setConfigValues();
     84        this->setPriority( priority::very_high );
    6985        this->registerVariables();
    7086    }
     
    7490        if (this->isInitialized())
    7591        {
    76             if (this->bControlled_)
    77                 this->stopLocalControl();
     92            this->bDestroyWhenPlayerLeft_ = false;
     93
     94            if (this->bHasLocalController_ && this->bHasHumanController_)
     95                this->stopLocalHumanControl();
     96
     97            if (this->getPlayer() && this->getPlayer()->getControllableEntity() == this)
     98                this->getPlayer()->stopControl(this, false);
    7899
    79100            if (this->hud_)
     
    83104                delete this->camera_;
    84105
    85             if (this->getPlayer() && this->getPlayer()->getControllableEntity() == this)
    86                 this->getPlayer()->stopControl(this, false);
     106            for (std::list<CameraPosition*>::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
     107                delete (*it);
     108
     109            if (this->getScene()->getSceneManager())
     110                this->getScene()->getSceneManager()->destroySceneNode(this->cameraPositionRootNode_->getName());
    87111        }
    88112    }
     
    98122    }
    99123
     124    void ControllableEntity::setConfigValues()
     125    {
     126        SetConfigValue(mouseLookSpeed_, 3.0f);
     127    }
     128
     129    void ControllableEntity::changedGametype()
     130    {
     131        //SUPER(ControllableEntity, changedGametype);
     132        WorldEntity::changedGametype();
     133
     134        this->gtinfo_ = 0;
     135        this->gtinfoID_ = OBJECTID_UNKNOWN;
     136
     137        if (this->getGametype() && this->getGametype()->getGametypeInfo())
     138        {
     139            this->gtinfo_ = this->getGametype()->getGametypeInfo();
     140            this->gtinfoID_ = this->gtinfo_->getObjectID();
     141        }
     142    }
     143
    100144    void ControllableEntity::addCameraPosition(CameraPosition* position)
    101145    {
    102         this->attach(position);
     146        if (position->getAllowMouseLook())
     147            position->attachToNode(this->cameraPositionRootNode_);
     148        else
     149            this->attach(position);
    103150        this->cameraPositions_.push_back(position);
    104151    }
     
    141188            else
    142189            {
    143                 this->attach(this->camera_);
     190                this->camera_->attachToNode(this->cameraPositionRootNode_);
    144191            }
    145192        }
     193    }
     194
     195    void ControllableEntity::mouseLook()
     196    {
     197        this->bMouseLook_ = !this->bMouseLook_;
     198
     199        if (!this->bMouseLook_)
     200            this->cameraPositionRootNode_->setOrientation(Quaternion::IDENTITY);
     201    }
     202
     203    void ControllableEntity::rotateYaw(const Vector2& value)
     204    {
     205        if (this->bMouseLook_)
     206            this->cameraPositionRootNode_->yaw(Radian(value.y * this->mouseLookSpeed_), Ogre::Node::TS_LOCAL);
     207    }
     208
     209    void ControllableEntity::rotatePitch(const Vector2& value)
     210    {
     211        if (this->bMouseLook_)
     212            this->cameraPositionRootNode_->pitch(Radian(value.y * this->mouseLookSpeed_), Ogre::Node::TS_LOCAL);
     213    }
     214
     215    void ControllableEntity::rotateRoll(const Vector2& value)
     216    {
     217        if (this->bMouseLook_)
     218            this->cameraPositionRootNode_->roll(Radian(value.y * this->mouseLookSpeed_), Ogre::Node::TS_LOCAL);
    146219    }
    147220
     
    156229        this->player_ = player;
    157230        this->playerID_ = player->getObjectID();
    158         this->bControlled_ = (player->isLocalPlayer() && player->isHumanPlayer());
    159         if (this->bControlled_)
    160         {
    161             this->startLocalControl();
     231        this->bHasLocalController_ = player->isLocalPlayer();
     232        this->bHasHumanController_ = player->isHumanPlayer();
     233
     234        if (this->bHasLocalController_ && this->bHasHumanController_)
     235        {
     236            this->startLocalHumanControl();
    162237
    163238            if (!Core::isMaster())
    164239            {
    165240                this->client_overwrite_ = this->server_overwrite_;
    166 COUT(0) << "CE: bidirectional synchronization" << std::endl;
    167                 this->setObjectMode(direction::bidirectional);
     241                this->setObjectMode(objectDirection::bidirectional);
    168242            }
    169243        }
     
    172246    void ControllableEntity::removePlayer()
    173247    {
    174         if (this->bControlled_)
    175             this->stopLocalControl();
     248        if (this->bHasLocalController_ && this->bHasHumanController_)
     249            this->stopLocalHumanControl();
    176250
    177251        this->player_ = 0;
    178252        this->playerID_ = OBJECTID_UNKNOWN;
    179         this->bControlled_ = false;
    180         this->setObjectMode(direction::toclient);
     253        this->bHasLocalController_ = false;
     254        this->bHasHumanController_ = false;
     255        this->setObjectMode(objectDirection::toclient);
    181256
    182257        if (this->bDestroyWhenPlayerLeft_)
     
    195270    }
    196271
    197     void ControllableEntity::startLocalControl()
    198     {
    199 //        std::cout << this->getObjectID() << " ###### start local control" << std::endl;
    200         this->camera_ = new Camera(this);
    201         this->camera_->requestFocus();
    202         if (this->cameraPositionTemplate_ != "")
    203             this->addTemplate(this->cameraPositionTemplate_);
    204         if (this->cameraPositions_.size() > 0)
    205             this->cameraPositions_.front()->attachCamera(this->camera_);
    206         else
    207             this->attach(this->camera_);
    208 
    209         if (this->hudtemplate_ != "")
    210         {
    211             this->hud_ = new OverlayGroup(this);
    212             this->hud_->addTemplate(this->hudtemplate_);
    213         }
    214     }
    215 
    216     void ControllableEntity::stopLocalControl()
    217     {
    218 //        std::cout << "###### stop local control" << std::endl;
    219         this->camera_->detachFromParent();
    220         delete this->camera_;
    221         this->camera_ = 0;
    222 
    223         delete this->hud_;
    224         this->hud_ = 0;
     272    void ControllableEntity::networkcallback_changedgtinfoID()
     273    {
     274        if (this->gtinfoID_ != OBJECTID_UNKNOWN)
     275        {
     276            this->gtinfo_ = dynamic_cast<GametypeInfo*>(Synchronisable::getSynchronisable(this->gtinfoID_));
     277
     278            if (!this->gtinfo_)
     279                this->gtinfoID_ = OBJECTID_UNKNOWN;
     280        }
     281    }
     282
     283    void ControllableEntity::startLocalHumanControl()
     284    {
     285        if (!this->camera_)
     286        {
     287            this->camera_ = new Camera(this);
     288            this->camera_->requestFocus();
     289            if (this->cameraPositionTemplate_ != "")
     290                this->addTemplate(this->cameraPositionTemplate_);
     291            if (this->cameraPositions_.size() > 0)
     292                this->cameraPositions_.front()->attachCamera(this->camera_);
     293            else
     294                this->camera_->attachToNode(this->cameraPositionRootNode_);
     295        }
     296
     297        if (!this->hud_)
     298        {
     299            if (this->hudtemplate_ != "")
     300            {
     301                this->hud_ = new OverlayGroup(this);
     302                this->hud_->addTemplate(this->hudtemplate_);
     303                this->hud_->setOwner(this);
     304            }
     305        }
     306    }
     307
     308    void ControllableEntity::stopLocalHumanControl()
     309    {
     310        if (this->camera_)
     311        {
     312            this->camera_->detachFromParent();
     313            delete this->camera_;
     314            this->camera_ = 0;
     315        }
     316
     317        if (this->hud_)
     318        {
     319            delete this->hud_;
     320            this->hud_ = 0;
     321        }
    225322    }
    226323
    227324    void ControllableEntity::tick(float dt)
    228325    {
     326        MobileEntity::tick(dt);
     327
    229328        if (this->isActive())
    230329        {
    231             this->velocity_ += (dt * this->acceleration_);
    232             this->node_->translate(dt * this->velocity_, Ogre::Node::TS_LOCAL);
    233 
    234             if (Core::isMaster())
     330            // Check whether Bullet doesn't do the physics for us
     331            if (!this->isDynamic())
    235332            {
    236                 this->server_velocity_ = this->velocity_;
    237                 this->server_position_ = this->node_->getPosition();
     333                if (Core::isMaster())
     334                {
     335                    this->server_position_ = this->getPosition();
     336                    this->server_orientation_ = this->getOrientation();
     337                    this->server_linear_velocity_ = this->getVelocity();
     338                    this->server_angular_velocity_ = this->getAngularVelocity();
     339                }
     340                else if (this->bHasLocalController_)
     341                {
     342                    this->client_position_ = this->getPosition();
     343                    this->client_orientation_ = this->getOrientation();
     344                    this->client_linear_velocity_ = this->getVelocity();
     345                    this->client_angular_velocity_ = this->getAngularVelocity();
     346                }
    238347            }
    239             else if (this->bControlled_)
    240             {
    241 //                COUT(2) << "setting client position" << endl;
    242                 this->client_velocity_ = this->velocity_;
    243                 this->client_position_ = this->node_->getPosition();
    244             }
    245348        }
    246349    }
     
    248351    void ControllableEntity::registerVariables()
    249352    {
    250         REGISTERSTRING(this->cameraPositionTemplate_, direction::toclient);
    251 
    252         REGISTERDATA(this->client_overwrite_,   direction::toserver);
    253        
    254         REGISTERDATA(this->server_position_,    direction::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerPosition));
    255         REGISTERDATA(this->server_velocity_,    direction::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerVelocity));
    256         REGISTERDATA(this->server_orientation_, direction::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerOrientation));
    257         REGISTERDATA(this->server_overwrite_,   direction::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processOverwrite));
    258 
    259         REGISTERDATA(this->client_position_,    direction::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientPosition));
    260         REGISTERDATA(this->client_velocity_,    direction::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientVelocity));
    261         REGISTERDATA(this->client_orientation_, direction::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientOrientation));
    262 
    263 
    264         REGISTERDATA(this->playerID_, direction::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::networkcallback_changedplayerID));
     353        registerVariable(this->cameraPositionTemplate_,  variableDirection::toclient);
     354        registerVariable(this->hudtemplate_,             variableDirection::toclient);
     355
     356        registerVariable(this->server_position_,         variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerPosition));
     357        registerVariable(this->server_linear_velocity_,  variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerLinearVelocity));
     358        registerVariable(this->server_orientation_,      variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerOrientation));
     359        registerVariable(this->server_angular_velocity_, variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processServerAngularVelocity));
     360
     361        registerVariable(this->server_overwrite_,        variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processOverwrite));
     362        registerVariable(this->client_overwrite_,        variableDirection::toserver);
     363
     364        registerVariable(this->client_position_,         variableDirection::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientPosition));
     365        registerVariable(this->client_linear_velocity_,  variableDirection::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientLinearVelocity));
     366        registerVariable(this->client_orientation_,      variableDirection::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientOrientation));
     367        registerVariable(this->client_angular_velocity_, variableDirection::toserver, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::processClientAngularVelocity));
     368
     369        registerVariable(this->playerID_,                variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::networkcallback_changedplayerID));
     370        registerVariable(this->gtinfoID_,                variableDirection::toclient, new NetworkCallback<ControllableEntity>(this, &ControllableEntity::networkcallback_changedgtinfoID));
    265371    }
    266372
    267373    void ControllableEntity::processServerPosition()
    268374    {
    269         if (!this->bControlled_)
    270             this->node_->setPosition(this->server_position_);
    271     }
    272 
    273     void ControllableEntity::processServerVelocity()
    274     {
    275         if (!this->bControlled_)
    276             this->velocity_ = this->server_velocity_;
     375        if (!this->bHasLocalController_)
     376            MobileEntity::setPosition(this->server_position_);
     377    }
     378
     379    void ControllableEntity::processServerLinearVelocity()
     380    {
     381        if (!this->bHasLocalController_)
     382            MobileEntity::setVelocity(this->server_linear_velocity_);
    277383    }
    278384
    279385    void ControllableEntity::processServerOrientation()
    280386    {
    281         if (!this->bControlled_)
    282             this->node_->setOrientation(this->server_orientation_);
     387        if (!this->bHasLocalController_)
     388            MobileEntity::setOrientation(this->server_orientation_);
     389    }
     390
     391    void ControllableEntity::processServerAngularVelocity()
     392    {
     393        if (!this->bHasLocalController_)
     394            MobileEntity::setAngularVelocity(this->server_angular_velocity_);
    283395    }
    284396
    285397    void ControllableEntity::processOverwrite()
    286398    {
    287         if (this->bControlled_)
     399        if (this->bHasLocalController_)
    288400        {
    289401            this->setPosition(this->server_position_);
    290             this->setVelocity(this->server_velocity_);
    291402            this->setOrientation(this->server_orientation_);
     403            this->setVelocity(this->server_linear_velocity_);
     404            this->setAngularVelocity(this->server_angular_velocity_);
    292405
    293406            this->client_overwrite_ = this->server_overwrite_;
     
    299412        if (this->server_overwrite_ == this->client_overwrite_)
    300413        {
    301 //            COUT(2) << "callback: setting client position" << endl;
    302             this->node_->setPosition(this->client_position_);
    303             this->server_position_ = this->client_position_;
    304         }
    305 //        else
    306 //          COUT(2) << "callback: not setting client position" << endl;
    307     }
    308 
    309     void ControllableEntity::processClientVelocity()
     414            MobileEntity::setPosition(this->client_position_);
     415            this->server_position_ = this->getPosition();
     416        }
     417    }
     418
     419    void ControllableEntity::processClientLinearVelocity()
    310420    {
    311421        if (this->server_overwrite_ == this->client_overwrite_)
    312422        {
    313             this->velocity_ = this->client_velocity_;
    314             this->server_velocity_ = this->client_velocity_;
     423            MobileEntity::setVelocity(this->client_linear_velocity_);
     424            this->server_linear_velocity_ = this->getVelocity();
    315425        }
    316426    }
     
    320430        if (this->server_overwrite_ == this->client_overwrite_)
    321431        {
    322             this->node_->setOrientation(this->client_orientation_);
    323             this->server_orientation_ = this->client_orientation_;
    324         }
    325     }
    326 
     432            MobileEntity::setOrientation(this->client_orientation_);
     433            this->server_orientation_ = this->getOrientation();
     434        }
     435    }
     436
     437    void ControllableEntity::processClientAngularVelocity()
     438    {
     439        if (this->server_overwrite_ == this->client_overwrite_)
     440        {
     441            MobileEntity::setAngularVelocity(this->client_angular_velocity_);
     442            this->server_angular_velocity_ = this->getAngularVelocity();
     443        }
     444    }
    327445
    328446    void ControllableEntity::setPosition(const Vector3& position)
     
    330448        if (Core::isMaster())
    331449        {
    332             this->node_->setPosition(position);
    333             this->server_position_ = position;
     450            MobileEntity::setPosition(position);
     451            this->server_position_ = this->getPosition();
    334452            ++this->server_overwrite_;
    335453        }
    336         else if (this->bControlled_)
    337         {
    338             this->node_->setPosition(position);
    339             this->client_position_ = position;
     454        else if (this->bHasLocalController_)
     455        {
     456            MobileEntity::setPosition(position);
     457            this->client_position_ = this->getPosition();
     458        }
     459    }
     460
     461    void ControllableEntity::setOrientation(const Quaternion& orientation)
     462    {
     463        if (Core::isMaster())
     464        {
     465            MobileEntity::setOrientation(orientation);
     466            this->server_orientation_ = this->getOrientation();
     467            ++this->server_overwrite_;
     468        }
     469        else if (this->bHasLocalController_)
     470        {
     471            MobileEntity::setOrientation(orientation);
     472            this->client_orientation_ = this->getOrientation();
    340473        }
    341474    }
     
    345478        if (Core::isMaster())
    346479        {
    347             this->velocity_ = velocity;
    348             this->server_velocity_ = velocity;
     480            MobileEntity::setVelocity(velocity);
     481            this->server_linear_velocity_ = this->getVelocity();
    349482            ++this->server_overwrite_;
    350483        }
    351         else if (this->bControlled_)
    352         {
    353             this->velocity_ = velocity;
    354             this->client_velocity_ = velocity;
    355         }
    356     }
    357 
    358     void ControllableEntity::translate(const Vector3& distance, Ogre::Node::TransformSpace relativeTo)
     484        else if (this->bHasLocalController_)
     485        {
     486            MobileEntity::setVelocity(velocity);
     487            this->client_linear_velocity_ = this->getVelocity();
     488        }
     489    }
     490
     491    void ControllableEntity::setAngularVelocity(const Vector3& velocity)
    359492    {
    360493        if (Core::isMaster())
    361494        {
    362             this->node_->translate(distance, relativeTo);
    363             this->server_position_ = this->node_->getPosition();
     495            MobileEntity::setAngularVelocity(velocity);
     496            this->server_angular_velocity_ = this->getAngularVelocity();
    364497            ++this->server_overwrite_;
    365498        }
    366         else if (this->bControlled_)
    367         {
    368             this->node_->translate(distance, relativeTo);
    369             this->client_position_ = this->node_->getPosition();
    370         }
    371     }
    372 
    373     void ControllableEntity::setOrientation(const Quaternion& orientation)
    374     {
     499        else if (this->bHasLocalController_)
     500        {
     501            MobileEntity::setAngularVelocity(velocity);
     502            this->client_angular_velocity_ = this->getAngularVelocity();
     503        }
     504    }
     505
     506    void ControllableEntity::setWorldTransform(const btTransform& worldTrans)
     507    {
     508        MobileEntity::setWorldTransform(worldTrans);
    375509        if (Core::isMaster())
    376510        {
    377             this->node_->setOrientation(orientation);
    378             this->server_orientation_ = orientation;
    379             ++this->server_overwrite_;
    380         }
    381         else if (this->bControlled_)
    382         {
    383             this->node_->setOrientation(orientation);
    384             this->client_orientation_ = orientation;
    385         }
    386     }
    387 
    388     void ControllableEntity::rotate(const Quaternion& rotation, Ogre::Node::TransformSpace relativeTo)
    389     {
    390         if (Core::isMaster())
    391         {
    392             this->node_->rotate(rotation, relativeTo);
    393             this->server_orientation_ = this->node_->getOrientation();
    394             ++this->server_overwrite_;
    395         }
    396         else if (this->bControlled_)
    397         {
    398             this->node_->rotate(rotation, relativeTo);
    399             this->client_orientation_ = this->node_->getOrientation();
    400         }
    401     }
    402 
    403     void ControllableEntity::yaw(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    404     {
    405         if (Core::isMaster())
    406         {
    407             this->node_->yaw(angle, relativeTo);
    408             this->server_orientation_ = this->node_->getOrientation();
    409             ++this->server_overwrite_;
    410         }
    411         else if (this->bControlled_)
    412         {
    413             this->node_->yaw(angle, relativeTo);
    414             this->client_orientation_ = this->node_->getOrientation();
    415         }
    416     }
    417 
    418     void ControllableEntity::pitch(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    419     {
    420         if (Core::isMaster())
    421         {
    422             this->node_->pitch(angle, relativeTo);
    423             this->server_orientation_ = this->node_->getOrientation();
    424             ++this->server_overwrite_;
    425         }
    426         else if (this->bControlled_)
    427         {
    428             this->node_->pitch(angle, relativeTo);
    429             this->client_orientation_ = this->node_->getOrientation();
    430         }
    431     }
    432 
    433     void ControllableEntity::roll(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    434     {
    435         if (Core::isMaster())
    436         {
    437             this->node_->roll(angle, relativeTo);
    438             this->server_orientation_ = this->node_->getOrientation();
    439             ++this->server_overwrite_;
    440         }
    441         else if (this->bControlled_)
    442         {
    443             this->node_->roll(angle, relativeTo);
    444             this->client_orientation_ = this->node_->getOrientation();
    445         }
    446     }
    447 
    448     void ControllableEntity::lookAt(const Vector3& target, Ogre::Node::TransformSpace relativeTo, const Vector3& localDirectionVector)
    449     {
    450         if (Core::isMaster())
    451         {
    452             this->node_->lookAt(target, relativeTo, localDirectionVector);
    453             this->server_orientation_ = this->node_->getOrientation();
    454             ++this->server_overwrite_;
    455         }
    456         else if (this->bControlled_)
    457         {
    458             this->node_->lookAt(target, relativeTo, localDirectionVector);
    459             this->client_orientation_ = this->node_->getOrientation();
    460         }
    461     }
    462 
    463     void ControllableEntity::setDirection(const Vector3& direction, Ogre::Node::TransformSpace relativeTo, const Vector3& localDirectionVector)
    464     {
    465         if (Core::isMaster())
    466         {
    467             this->node_->setDirection(direction, relativeTo, localDirectionVector);
    468             this->server_orientation_ = this->node_->getOrientation();
    469             ++this->server_overwrite_;
    470         }
    471         else if (this->bControlled_)
    472         {
    473             this->node_->setDirection(direction, relativeTo, localDirectionVector);
    474             this->client_orientation_ = this->node_->getOrientation();
     511            this->server_position_ = this->getPosition();
     512            this->server_orientation_ = this->getOrientation();
     513            this->server_linear_velocity_ = this->getVelocity();
     514            this->server_angular_velocity_ = this->getAngularVelocity();
     515        }
     516        else if (this->bHasLocalController_)
     517        {
     518            this->client_position_ = this->getPosition();
     519            this->client_orientation_ = this->getOrientation();
     520            this->client_linear_velocity_ = this->getVelocity();
     521            this->client_angular_velocity_ = this->getAngularVelocity();
    475522        }
    476523    }
  • code/trunk/src/orxonox/objects/worldentities/ControllableEntity.h

    r2087 r2662  
    2323 *      Fabian 'x3n' Landau
    2424 *   Co-authors:
    25  *      ...
     25 *      Reto Grieder
    2626 *
    2727 */
     
    3232#include "OrxonoxPrereqs.h"
    3333
    34 #include "WorldEntity.h"
    35 #include "objects/Tickable.h"
     34#include "MobileEntity.h"
     35#include "objects/weaponSystem/WeaponSystem.h"
    3636
    3737namespace orxonox
    3838{
    39     class _OrxonoxExport ControllableEntity : public WorldEntity, public Tickable
     39    class _OrxonoxExport ControllableEntity : public MobileEntity
    4040    {
    4141        public:
     
    4646            virtual void tick(float dt);
    4747            void registerVariables();
     48            void setConfigValues();
     49
     50            virtual void changedGametype();
    4851
    4952            virtual void setPlayer(PlayerInfo* player);
     
    6164            virtual void moveUpDown(const Vector2& value) {}
    6265
    63             virtual void rotateYaw(const Vector2& value) {}
    64             virtual void rotatePitch(const Vector2& value) {}
    65             virtual void rotateRoll(const Vector2& value) {}
     66            virtual void rotateYaw(const Vector2& value);
     67            virtual void rotatePitch(const Vector2& value);
     68            virtual void rotateRoll(const Vector2& value);
    6669
    67             virtual void fire() {}
    68             virtual void altFire() {}
     70            inline void moveFrontBack(float value)
     71                { this->moveFrontBack(Vector2(value, 0)); }
     72            inline void moveRightLeft(float value)
     73                { this->moveRightLeft(Vector2(value, 0)); }
     74            inline void moveUpDown(float value)
     75                { this->moveUpDown(Vector2(value, 0)); }
    6976
     77            inline void rotateYaw(float value)
     78                { this->rotateYaw(Vector2(value, 0)); }
     79            inline void rotatePitch(float value)
     80                { this->rotatePitch(Vector2(value, 0)); }
     81            inline void rotateRoll(float value)
     82                { this->rotateRoll(Vector2(value, 0)); }
     83
     84            virtual void fire(WeaponMode::Enum fireMode) {}
     85            virtual void altFire(WeaponMode::Enum fireMode) {}
     86
     87            virtual void boost() {}
    7088            virtual void greet() {}
    7189            virtual void use() {}
     90            virtual void dropItems() {}
    7291            virtual void switchCamera();
     92            virtual void mouseLook();
    7393
    74             inline const Vector3& getVelocity() const
    75                 { return this->velocity_; }
    76             inline const Vector3& getAcceleration() const
    77                 { return this->acceleration_; }
    7894            inline const std::string& getHudTemplate() const
    7995                { return this->hudtemplate_; }
    80 
    81             using WorldEntity::setPosition;
    82             using WorldEntity::translate;
    83             using WorldEntity::setOrientation;
    84             using WorldEntity::rotate;
    85             using WorldEntity::yaw;
    86             using WorldEntity::pitch;
    87             using WorldEntity::roll;
    88             using WorldEntity::lookAt;
    89             using WorldEntity::setDirection;
    90 
    91             void setPosition(const Vector3& position);
    92             void translate(const Vector3& distance, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    93             void setOrientation(const Quaternion& orientation);
    94             void rotate(const Quaternion& rotation, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    95             void yaw(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    96             void pitch(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    97             void roll(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    98             void lookAt(const Vector3& target, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
    99             void setDirection(const Vector3& direction, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
    100 
    101             void setVelocity(const Vector3& velocity);
    102             inline void setVelocity(float x, float y, float z)
    103                 { this->velocity_.x = x; this->velocity_.y = y; this->velocity_.z = z; }
    104 
    105             inline void setAcceleration(const Vector3& acceleration)
    106                 { this->acceleration_ = acceleration; }
    107             inline void setAcceleration(float x, float y, float z)
    108                 { this->acceleration_.x = x; this->acceleration_.y = y; this->acceleration_.z = z; }
    10996
    11097            inline Camera* getCamera() const
     
    123110                { return this->cameraPositionTemplate_; }
    124111
     112            using WorldEntity::setPosition;
     113            using WorldEntity::setOrientation;
     114            using MobileEntity::setVelocity;
     115            using MobileEntity::setAngularVelocity;
     116
     117            void setPosition(const Vector3& position);
     118            void setOrientation(const Quaternion& orientation);
     119            void setVelocity(const Vector3& velocity);
     120            void setAngularVelocity(const Vector3& velocity);
     121
     122            inline bool hasLocalController() const
     123                { return this->bHasLocalController_; }
     124            inline bool hasHumanController() const
     125                { return this->bHasHumanController_; }
     126
     127            inline const GametypeInfo* getGametypeInfo() const
     128                { return this->gtinfo_; }
     129
     130            inline bool isInMouseLook() const
     131                { return this->bMouseLook_; }
     132            inline float getMouseLookSpeed() const
     133                { return this->mouseLookSpeed_; }
     134
    125135        protected:
    126             virtual void startLocalControl();
    127             virtual void stopLocalControl();
     136            virtual void startLocalHumanControl();
     137            virtual void stopLocalHumanControl();
    128138
    129139            inline void setHudTemplate(const std::string& name)
    130140                { this->hudtemplate_ = name; }
    131 
    132             inline bool isLocallyControlled() const
    133                 { return this->bControlled_; }
    134 
    135             Vector3 acceleration_;
    136141
    137142        private:
     
    140145
    141146            void processServerPosition();
    142             void processServerVelocity();
     147            void processServerLinearVelocity();
    143148            void processServerOrientation();
     149            void processServerAngularVelocity();
    144150
    145151            void processClientPosition();
    146             void processClientVelocity();
     152            void processClientLinearVelocity();
    147153            void processClientOrientation();
     154            void processClientAngularVelocity();
    148155
    149156            void networkcallback_changedplayerID();
     157            void networkcallback_changedgtinfoID();
     158
     159            // Bullet btMotionState related
     160            void setWorldTransform(const btTransform& worldTrans);
    150161
    151162            unsigned int server_overwrite_;
    152163            unsigned int client_overwrite_;
    153164
    154             Vector3 velocity_;
     165            bool bHasLocalController_;
     166            bool bHasHumanController_;
     167            bool bDestroyWhenPlayerLeft_;
    155168
    156             bool bControlled_;
    157169            Vector3 server_position_;
    158170            Vector3 client_position_;
    159             Vector3 server_velocity_;
    160             Vector3 client_velocity_;
     171            Vector3 server_linear_velocity_;
     172            Vector3 client_linear_velocity_;
    161173            Quaternion server_orientation_;
    162174            Quaternion client_orientation_;
     175            Vector3 server_angular_velocity_;
     176            Vector3 client_angular_velocity_;
    163177
    164178            PlayerInfo* player_;
    165179            unsigned int playerID_;
     180
    166181            std::string hudtemplate_;
    167182            OverlayGroup* hud_;
     183
    168184            Camera* camera_;
    169             bool bDestroyWhenPlayerLeft_;
    170 
     185            bool bMouseLook_;
     186            float mouseLookSpeed_;
     187            Ogre::SceneNode* cameraPositionRootNode_;
    171188            std::list<CameraPosition*> cameraPositions_;
    172189            std::string cameraPositionTemplate_;
     190
     191            const GametypeInfo* gtinfo_;
     192            unsigned int gtinfoID_;
    173193    };
    174194}
  • code/trunk/src/orxonox/objects/worldentities/Light.cc

    r2171 r2662  
    3636
    3737#include "util/String.h"
    38 #include "util/Convert.h"
     38#include "util/Exception.h"
     39#include "core/Core.h"
    3940#include "core/CoreIncludes.h"
    4041#include "core/XMLPort.h"
     
    4344namespace orxonox
    4445{
    45     unsigned int Light::lightCounter_s = 0;
    46 
    4746    CreateFactory(Light);
    4847
    49     Light::Light(BaseObject* creator) : PositionableEntity(creator)
     48    Light::Light(BaseObject* creator) : StaticEntity(creator)
    5049    {
    5150        RegisterObject(Light);
    5251
    53         if (this->getScene() && this->getScene()->getSceneManager())
    54         this->light_ = this->getScene()->getSceneManager()->createLight("Light" + convertToString(Light::lightCounter_s++));
    55         this->getNode()->attachObject(this->light_);
     52        this->light_ = 0;
     53        this->diffuse_ = ColourValue::White;
     54        this->specular_ = ColourValue::White;
     55        this->type_ = Ogre::Light::LT_POINT;
     56        this->attenuation_ = Vector4(100000, 1, 0, 0);
     57        this->spotlightRange_ = Vector3(40.0f, 30.0f, 1.0f);
     58
     59        if (Core::showsGraphics())
     60        {
     61            if (!this->getScene())
     62                ThrowException(AbortLoading, "Can't create Light, no scene given.");
     63            if (!this->getScene()->getSceneManager())
     64                ThrowException(AbortLoading, "Can't create Light, no scene manager given.");
     65
     66            if (this->getScene() && this->getScene()->getSceneManager())
     67            {
     68                this->light_ = this->getScene()->getSceneManager()->createLight("Light" + getUniqueNumberString());
     69                this->light_->setDirection(WorldEntity::FRONT);
     70                this->attachOgreObject(this->light_);
     71
     72                this->updateType();
     73                this->updateDiffuseColour();
     74                this->updateSpecularColour();
     75                this->updateAttenuation();
     76                this->updateSpotlightRange();
     77            }
     78        }
    5679
    5780        this->registerVariables();
     
    7194        SUPER(Light, XMLPort, xmlelement, mode);
    7295
    73         XMLPortParam(Light, "type", setTypeString, getTypeString, xmlelement, mode).defaultValues("point");
    74         XMLPortParamExternTemplate(Light, Ogre::Light, this->light_, "diffuse",   setDiffuseColour,  getDiffuseColour,  xmlelement, mode, const ColourValue&);
    75         XMLPortParamExternTemplate(Light, Ogre::Light, this->light_, "specular",  setSpecularColour, getSpecularColour, xmlelement, mode, const ColourValue&);
    76         XMLPortParamExternTemplate(Light, Ogre::Light, this->light_, "direction", setDirection,      getDirection,      xmlelement, mode, const Vector3&);
     96        XMLPortParam(Light, "type",           setTypeString,     getTypeString,     xmlelement, mode).defaultValues("point");
     97        XMLPortParam(Light, "diffuse",        setDiffuseColour,  getDiffuseColour,  xmlelement, mode).defaultValues(ColourValue::White);
     98        XMLPortParam(Light, "specular",       setSpecularColour, getSpecularColour, xmlelement, mode).defaultValues(ColourValue::White);
     99        XMLPortParam(Light, "attenuation",    setAttenuation,    getAttenuation,    xmlelement, mode).defaultValues(Vector4(100000, 1, 0, 0));
     100        XMLPortParam(Light, "spotlightrange", setSpotlightRange, getSpotlightRange, xmlelement, mode).defaultValues(Vector3(40.0f, 30.0f, 1.0f));
    77101    }
    78102
    79103    void Light::registerVariables()
    80104    {
    81         REGISTERDATA(this->type_, direction::toclient, new NetworkCallback<Light>(this, &Light::changedType));
    82         REGISTERDATA(this->light_->getDiffuseColour(), direction::toclient);
    83         REGISTERDATA(this->light_->getSpecularColour(), direction::toclient);
    84         REGISTERDATA(this->light_->getDirection(), direction::toclient);
     105        registerVariable((int&)this->type_,     variableDirection::toclient, new NetworkCallback<Light>(this, &Light::updateType));
     106        registerVariable(this->diffuse_,        variableDirection::toclient, new NetworkCallback<Light>(this, &Light::updateDiffuseColour));
     107        registerVariable(this->specular_,       variableDirection::toclient, new NetworkCallback<Light>(this, &Light::updateSpecularColour));
     108        registerVariable(this->attenuation_,    variableDirection::toclient, new NetworkCallback<Light>(this, &Light::updateAttenuation));
     109        registerVariable(this->spotlightRange_, variableDirection::toclient, new NetworkCallback<Light>(this, &Light::updateSpotlightRange));
    85110    }
    86111
    87     const std::string& Light::getName() const
     112    void Light::updateDiffuseColour()
    88113    {
    89114        if (this->light_)
    90             return this->light_->getName();
    91         else
    92             return BLANKSTRING;
     115            this->light_->setDiffuseColour(this->diffuse_);
    93116    }
    94117
    95     void Light::setDiffuseColour(const ColourValue& colour)
     118    void Light::updateSpecularColour()
    96119    {
    97120        if (this->light_)
    98             this->light_->setDiffuseColour(colour);
     121            this->light_->setSpecularColour(this->specular_);
    99122    }
    100123
    101     const ColourValue& Light::getDiffuseColour() const
     124    void Light::updateAttenuation()
    102125    {
    103         if (this->light_)
    104             return this->light_->getDiffuseColour();
    105         else
    106             return ColourValue::White;
     126        if (this->light_ && this->type_ != Ogre::Light::LT_DIRECTIONAL)
     127            this->light_->setAttenuation(this->attenuation_.x, this->attenuation_.y, this->attenuation_.z, this->attenuation_.w);
    107128    }
    108129
    109     void Light::setSpecularColour(const ColourValue& colour)
     130    void Light::updateSpotlightRange()
    110131    {
    111         if (this->light_)
    112             this->light_->setSpecularColour(colour);
    113     }
    114 
    115     const ColourValue& Light::getSpecularColour() const
    116     {
    117         if (this->light_)
    118             return this->light_->getSpecularColour();
    119         else
    120             return ColourValue::White;
    121     }
    122 
    123     void Light::setDirection(const Vector3& direction)
    124     {
    125         if (this->light_)
    126             this->light_->setDirection(direction);
    127     }
    128 
    129     const Vector3& Light::getDirection() const
    130     {
    131         if (this->light_)
    132             return this->light_->getDirection();
    133         else
    134             return Vector3::ZERO;
     132        if (this->light_ && this->type_ == Ogre::Light::LT_SPOTLIGHT)
     133            this->light_->setSpotlightRange(Degree(this->spotlightRange_.x), Degree(this->spotlightRange_.y), this->spotlightRange_.z);
    135134    }
    136135
     
    157156            case Ogre::Light::LT_POINT:
    158157            default:
    159                 return "poinT";
     158                return "point";
    160159        }
    161160    }
    162161
    163     void Light::changedType()
     162    void Light::updateType()
    164163    {
    165         this->light_->setType(this->type_);
     164        if (this->light_)
     165        {
     166            this->light_->setType(this->type_);
     167
     168            if (this->type_ != Ogre::Light::LT_DIRECTIONAL)
     169                this->updateAttenuation();
     170            if (this->type_ == Ogre::Light::LT_SPOTLIGHT)
     171                this->updateSpotlightRange();
     172        }
    166173    }
    167174
     
    170177        SUPER(Light, changedVisibility);
    171178
    172         this->light_->setVisible(this->isVisible());
     179        if (this->light_)
     180            this->light_->setVisible(this->isVisible());
    173181    }
    174182}
  • code/trunk/src/orxonox/objects/worldentities/Light.h

    r2087 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 #include "PositionableEntity.h"
     33#include "StaticEntity.h"
    3434
    3535#include <string>
     
    4040namespace orxonox
    4141{
    42     class _OrxonoxExport Light : public PositionableEntity
     42    class _OrxonoxExport Light : public StaticEntity
    4343    {
    4444        public:
     
    5454                { return this->light_; }
    5555
    56             const std::string& getName() const;
    57 
    5856            inline void setType(Ogre::Light::LightTypes type)
    59                 { this->type_ = type; this->changedType(); }
    60             Ogre::Light::LightTypes getType() const
     57                { this->type_ = type; this->updateType(); }
     58            inline Ogre::Light::LightTypes getType() const
    6159                { return this->type_; }
    6260
    63             void setDiffuseColour(const ColourValue& colour);
    64             const ColourValue& getDiffuseColour() const;
     61            inline void setDiffuseColour(const ColourValue& colour)
     62                { this->diffuse_ = colour; this->updateDiffuseColour(); }
     63            inline const ColourValue& getDiffuseColour() const
     64                { return this->diffuse_; }
    6565
    66             void setSpecularColour(const ColourValue& colour);
    67             const ColourValue& getSpecularColour() const;
     66            inline void setSpecularColour(const ColourValue& colour)
     67                { this->specular_ = colour; this->updateSpecularColour(); }
     68            inline const ColourValue& getSpecularColour() const
     69                { return this->specular_; }
    6870
    69             void setDirection(const Vector3& direction);
    70             const Vector3& getDirection() const;
     71            /**
     72                @brief Sets the attenuation parameters of the light source i.e. how it diminishes with distance.
     73
     74                @param attenuation.x range (The absolute upper range of the light in world units)
     75                @param attenuation.y constant (The constant factor in the attenuation formula: 1.0 means never attenuate, 0.0 is complete attenuation)
     76                @param attenuation.z linear (The linear factor in the attenuation formula: 1 means attenuate evenly over the distance)
     77                @param attenuation.w quadratic (The quadratic factor in the attenuation formula: adds a curvature to the attenuation formula)
     78
     79                Quote from the Ogre API:
     80                Lights normally get fainter the further they are away. Also, each light is given a maximum range beyond which it cannot affect any objects.
     81                Light attenuation is not applicable to directional lights since they have an infinite range and constant intensity.
     82                This follows a standard attenuation approach - see any good 3D text for the details of what they mean since i don't have room here!
     83
     84                Quote from the Ogre wiki:
     85                "Using these numbers, the light has 100% intensity at 0 distance, and
     86                trails off to near black at a distance equal to the Range. Keep in mind
     87                that most of the light falls in the first 20% of the range."
     88
     89                Range   Constant   Linear     Quadratic
     90                3250,     1.0,     0.0014,    0.000007
     91                600,      1.0,     0.007,     0.0002
     92                325,      1.0,     0.014,     0.0007
     93                200,      1.0,     0.022,     0.0019
     94                160,      1.0,     0.027,     0.0028
     95                100,      1.0,     0.045,     0.0075
     96                65,       1.0,     0.07,      0.017
     97                50,       1.0,     0.09,      0.032
     98                32,       1.0,     0.14,      0.07
     99                20,       1.0,     0.22,      0.20
     100                13,       1.0,     0.35,      0.44
     101                7,        1.0,     0.7,       1.8
     102            */
     103            inline void setAttenuation(const Vector4& attenuation)
     104                { this->attenuation_ = attenuation; this->updateAttenuation(); }
     105            inline const Vector4& getAttenuation() const
     106                { return this->attenuation_; }
     107
     108            /**
     109                @brief Sets the range of a spotlight, i.e. the angle of the inner and outer cones and the rate of falloff between them.
     110
     111                @param spotlightRange.x innerAngle (The angle covered by the bright inner cone)
     112                @param spotlightRange.x outerAngle (The angle covered by the outer cone)
     113                @param spotlightRange.x falloff (The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, less means slower falloff, higher means faster falloff.)
     114            */
     115            inline void setSpotlightRange(const Vector3& spotlightRange)
     116                { this->spotlightRange_ = spotlightRange; this->updateSpotlightRange(); }
     117            inline const Vector3& getSpotlightRange() const
     118                { return this->spotlightRange_; }
    71119
    72120        private:
     
    74122            std::string getTypeString() const;
    75123
    76             void changedType();
     124            void updateType();
     125            void updateDiffuseColour();
     126            void updateSpecularColour();
     127            void updateAttenuation();
     128            void updateSpotlightRange();
    77129
    78             static unsigned int lightCounter_s;
    79130            Ogre::Light* light_;
    80131            Ogre::Light::LightTypes type_;
    81 
     132            ColourValue diffuse_;
     133            ColourValue specular_;
     134            Vector4 attenuation_;
     135            Vector3 spotlightRange_;
    82136    };
    83137}
  • code/trunk/src/orxonox/objects/worldentities/MobileEntity.cc

    • Property svn:mergeinfo changed (with no actual effect on merging)
  • code/trunk/src/orxonox/objects/worldentities/MobileEntity.h

    • Property svn:mergeinfo changed (with no actual effect on merging)
  • code/trunk/src/orxonox/objects/worldentities/Model.cc

    r2171 r2662  
    2929#include "OrxonoxStableHeaders.h"
    3030
     31#include <OgreEntity.h>
    3132#include "Model.h"
    3233#include "core/CoreIncludes.h"
     
    3839    CreateFactory(Model);
    3940
    40     Model::Model(BaseObject* creator) : PositionableEntity(creator)
     41    Model::Model(BaseObject* creator) : StaticEntity(creator)
    4142    {
    4243        RegisterObject(Model);
     44
     45        this->bCastShadows_ = true;
    4346
    4447        this->registerVariables();
     
    4851    {
    4952        if (this->isInitialized() && this->mesh_.getEntity())
    50             this->getNode()->detachObject(this->mesh_.getEntity());
     53            this->detachOgreObject(this->mesh_.getEntity());
    5154    }
    5255
     
    6164    void Model::registerVariables()
    6265    {
    63         REGISTERSTRING(this->meshSrc_,    direction::toclient, new NetworkCallback<Model>(this, &Model::changedMesh));
    64         REGISTERDATA(this->bCastShadows_, direction::toclient, new NetworkCallback<Model>(this, &Model::changedShadows));
     66        registerVariable(this->meshSrc_,    variableDirection::toclient, new NetworkCallback<Model>(this, &Model::changedMesh));
     67        registerVariable(this->bCastShadows_, variableDirection::toclient, new NetworkCallback<Model>(this, &Model::changedShadows));
    6568    }
    6669
    6770    void Model::changedMesh()
    6871    {
    69         if (this->mesh_.getEntity())
    70             this->getNode()->detachObject(this->mesh_.getEntity());
     72        if (Core::showsGraphics())
     73        {
     74            if (this->mesh_.getEntity())
     75                this->detachOgreObject(this->mesh_.getEntity());
    7176
    72         this->mesh_.setMeshSource(this->getScene()->getSceneManager(), this->meshSrc_);
     77            this->mesh_.setMeshSource(this->getScene()->getSceneManager(), this->meshSrc_);
    7378
    74         if (this->mesh_.getEntity())
    75         {
    76             this->getNode()->attachObject(this->mesh_.getEntity());
    77             this->mesh_.getEntity()->setCastShadows(this->bCastShadows_);
    78             this->mesh_.setVisible(this->isVisible());
     79            if (this->mesh_.getEntity())
     80            {
     81                this->attachOgreObject(this->mesh_.getEntity());
     82                this->mesh_.getEntity()->setCastShadows(this->bCastShadows_);
     83                this->mesh_.setVisible(this->isVisible());
     84            }
    7985        }
    8086    }
  • code/trunk/src/orxonox/objects/worldentities/Model.h

    r2087 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 #include "PositionableEntity.h"
     33#include "StaticEntity.h"
    3434#include "tools/Mesh.h"
    3535
    3636namespace orxonox
    3737{
    38     class _OrxonoxExport Model : public PositionableEntity
     38    class _OrxonoxExport Model : public StaticEntity
    3939    {
    4040        public:
     
    7070}
    7171
    72 #endif /* _PositionableEntity_H__ */
     72#endif /* _Model_H__ */
  • code/trunk/src/orxonox/objects/worldentities/MovableEntity.cc

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder
    2425 *   Co-authors:
    2526 *      ...
     
    3334#include "core/XMLPort.h"
    3435#include "core/Executor.h"
    35 #include "tools/Timer.h"
     36#include "core/Core.h"
    3637
    3738namespace orxonox
    3839{
    3940    static const float MAX_RESYNCHRONIZE_TIME = 3.0f;
     41    static const float CONTINUOUS_SYNCHRONIZATION_TIME = 10.0f;
    4042
    4143    CreateFactory(MovableEntity);
    4244
    43     MovableEntity::MovableEntity(BaseObject* creator) : WorldEntity(creator)
     45    MovableEntity::MovableEntity(BaseObject* creator) : MobileEntity(creator)
    4446    {
    4547        RegisterObject(MovableEntity);
    4648
    47         this->velocity_ = Vector3::ZERO;
    48         this->acceleration_ = Vector3::ZERO;
    49         this->rotationAxis_ = Vector3::ZERO;
    50         this->rotationRate_ = 0;
    51         this->momentum_ = 0;
     49        this->overwrite_position_    = Vector3::ZERO;
     50        this->overwrite_orientation_ = Quaternion::IDENTITY;
    5251
    53         this->overwrite_position_ = Vector3::ZERO;
    54         this->overwrite_orientation_ = Quaternion::IDENTITY;
     52        this->continuousResynchroTimer_ = 0;
     53
     54        this->setPriority(priority::low);
    5555
    5656        this->registerVariables();
     
    5959    MovableEntity::~MovableEntity()
    6060    {
     61        if (this->isInitialized())
     62            if (this->continuousResynchroTimer_)
     63                delete this->continuousResynchroTimer_;
    6164    }
    6265
     
    6467    {
    6568        SUPER(MovableEntity, XMLPort, xmlelement, mode);
    66 
    67         XMLPortParamTemplate(MovableEntity, "velocity", setVelocity, getVelocity, xmlelement, mode, const Vector3&);
    68         XMLPortParamTemplate(MovableEntity, "rotationaxis", setRotationAxis, getRotationAxis, xmlelement, mode, const Vector3&);
    69         XMLPortParamTemplate(MovableEntity, "rotationrate", setRotationRate, getRotationRate, xmlelement, mode, const Degree&);
    70     }
    71 
    72     void MovableEntity::tick(float dt)
    73     {
    74         if (this->isActive())
    75         {
    76             this->velocity_ += (dt * this->acceleration_);
    77             this->node_->translate(dt * this->velocity_);
    78 
    79             this->rotationRate_ += (dt * this->momentum_);
    80             this->node_->rotate(this->rotationAxis_, this->rotationRate_  * dt);
    81         }
    8269    }
    8370
    8471    void MovableEntity::registerVariables()
    8572    {
    86         REGISTERDATA(this->velocity_.x, direction::toclient);
    87         REGISTERDATA(this->velocity_.y, direction::toclient);
    88         REGISTERDATA(this->velocity_.z, direction::toclient);
     73        registerVariable(this->linearVelocity_,        variableDirection::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::processLinearVelocity));
     74        registerVariable(this->angularVelocity_,       variableDirection::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::processAngularVelocity));
    8975
    90         REGISTERDATA(this->rotationAxis_.x, direction::toclient);
    91         REGISTERDATA(this->rotationAxis_.y, direction::toclient);
    92         REGISTERDATA(this->rotationAxis_.z, direction::toclient);
    93 
    94         REGISTERDATA(this->rotationRate_, direction::toclient);
    95 
    96         REGISTERDATA(this->overwrite_position_,    direction::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::overwritePosition));
    97         REGISTERDATA(this->overwrite_orientation_, direction::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::overwriteOrientation));
    98     }
    99 
    100     void MovableEntity::overwritePosition()
    101     {
    102         this->node_->setPosition(this->overwrite_position_);
    103     }
    104 
    105     void MovableEntity::overwriteOrientation()
    106     {
    107         this->node_->setOrientation(this->overwrite_orientation_);
     76        registerVariable(this->overwrite_position_,    variableDirection::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::overwritePosition));
     77        registerVariable(this->overwrite_orientation_, variableDirection::toclient, new NetworkCallback<MovableEntity>(this, &MovableEntity::overwriteOrientation));
    10878    }
    10979
    11080    void MovableEntity::clientConnected(unsigned int clientID)
    11181    {
    112         new Timer<MovableEntity>(rnd() * MAX_RESYNCHRONIZE_TIME, false, this, createExecutor(createFunctor(&MovableEntity::resynchronize)), true);
     82        this->resynchronizeTimer_.setTimer(rnd() * MAX_RESYNCHRONIZE_TIME, false, this, createExecutor(createFunctor(&MovableEntity::resynchronize)));
    11383    }
    11484
     
    11989    void MovableEntity::resynchronize()
    12090    {
     91        if (Core::isMaster() && !this->continuousResynchroTimer_)
     92        {
     93            // Resynchronise every few seconds because we only work with velocities (no positions)
     94            continuousResynchroTimer_ = new Timer<MovableEntity>(CONTINUOUS_SYNCHRONIZATION_TIME + rnd(-1, 1),
     95                true, this, createExecutor(createFunctor(&MovableEntity::resynchronize)), false);
     96        }
     97
    12198        this->overwrite_position_ = this->getPosition();
    12299        this->overwrite_orientation_ = this->getOrientation();
    123100    }
    124 
    125     void MovableEntity::setPosition(const Vector3& position)
    126     {
    127         this->node_->setPosition(position);
    128         this->overwrite_position_ = this->node_->getPosition();
    129     }
    130 
    131     void MovableEntity::translate(const Vector3& distance, Ogre::Node::TransformSpace relativeTo)
    132     {
    133         this->node_->translate(distance, relativeTo);
    134         this->overwrite_position_ = this->node_->getPosition();
    135     }
    136 
    137     void MovableEntity::setOrientation(const Quaternion& orientation)
    138     {
    139         this->node_->setOrientation(orientation);
    140         this->overwrite_orientation_ = this->node_->getOrientation();
    141     }
    142 
    143     void MovableEntity::rotate(const Quaternion& rotation, Ogre::Node::TransformSpace relativeTo)
    144     {
    145         this->node_->rotate(rotation, relativeTo);
    146         this->overwrite_orientation_ = this->node_->getOrientation();
    147     }
    148 
    149     void MovableEntity::yaw(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    150     {
    151         this->node_->yaw(angle, relativeTo);
    152         this->overwrite_orientation_ = this->node_->getOrientation();
    153     }
    154 
    155     void MovableEntity::pitch(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    156     {
    157         this->node_->pitch(angle, relativeTo);
    158         this->overwrite_orientation_ = this->node_->getOrientation();
    159     }
    160 
    161     void MovableEntity::roll(const Degree& angle, Ogre::Node::TransformSpace relativeTo)
    162     {
    163         this->node_->roll(angle, relativeTo);
    164         this->overwrite_orientation_ = this->node_->getOrientation();
    165     }
    166 
    167     void MovableEntity::lookAt(const Vector3& target, Ogre::Node::TransformSpace relativeTo, const Vector3& localDirectionVector)
    168     {
    169         this->node_->lookAt(target, relativeTo, localDirectionVector);
    170         this->overwrite_orientation_ = this->node_->getOrientation();
    171     }
    172 
    173     void MovableEntity::setDirection(const Vector3& direction, Ogre::Node::TransformSpace relativeTo, const Vector3& localDirectionVector)
    174     {
    175         this->node_->setDirection(direction, relativeTo, localDirectionVector);
    176         this->overwrite_orientation_ = this->node_->getOrientation();
    177     }
    178101}
  • code/trunk/src/orxonox/objects/worldentities/MovableEntity.h

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder
    2425 *   Co-authors:
    2526 *      ...
     
    3233#include "OrxonoxPrereqs.h"
    3334
    34 #include "WorldEntity.h"
    35 #include "objects/Tickable.h"
     35#include "MobileEntity.h"
    3636#include "network/ClientConnectionListener.h"
     37#include "tools/Timer.h"
    3738
    3839namespace orxonox
    3940{
    40     class _OrxonoxExport MovableEntity : public WorldEntity, public Tickable, public ClientConnectionListener
     41    class _OrxonoxExport MovableEntity : public MobileEntity, public ClientConnectionListener
    4142    {
    4243        public:
     
    4546
    4647            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
    47             virtual void tick(float dt);
    4848            void registerVariables();
    4949
    5050            using WorldEntity::setPosition;
    51             using WorldEntity::translate;
    5251            using WorldEntity::setOrientation;
    53             using WorldEntity::rotate;
    54             using WorldEntity::yaw;
    55             using WorldEntity::pitch;
    56             using WorldEntity::roll;
    57             using WorldEntity::lookAt;
    58             using WorldEntity::setDirection;
    5952
    60             void setPosition(const Vector3& position);
    61             void translate(const Vector3& distance, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    62             void setOrientation(const Quaternion& orientation);
    63             void rotate(const Quaternion& rotation, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    64             void yaw(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    65             void pitch(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    66             void roll(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL);
    67             void lookAt(const Vector3& target, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
    68             void setDirection(const Vector3& direction, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
    69 
    70             inline void setVelocity(const Vector3& velocity)
    71                 { this->velocity_ = velocity; }
    72             inline void setVelocity(float x, float y, float z)
    73                 { this->velocity_.x = x; this->velocity_.y = y; this->velocity_.z = z; }
    74             inline const Vector3& getVelocity() const
    75                 { return this->velocity_; }
    76 
    77             inline void setAcceleration(const Vector3& acceleration)
    78                 { this->acceleration_ = acceleration; }
    79             inline void setAcceleration(float x, float y, float z)
    80                 { this->acceleration_.x = x; this->acceleration_.y = y; this->acceleration_.z = z; }
    81             inline const Vector3& getAcceleration() const
    82                 { return this->acceleration_; }
    83 
    84             inline void setRotationAxis(const Vector3& axis)
    85                 { this->rotationAxis_ = axis; this->rotationAxis_.normalise(); }
    86             inline void setRotationAxis(float x, float y, float z)
    87                 { this->rotationAxis_.x = x; this->rotationAxis_.y = y; this->rotationAxis_.z = z; rotationAxis_.normalise(); }
    88             inline const Vector3& getRotationAxis() const
    89                 { return this->rotationAxis_; }
    90 
    91             inline void setRotationRate(const Degree& angle)
    92                 { this->rotationRate_ = angle; }
    93             inline void setRotationRate(const Radian& angle)
    94                 { this->rotationRate_ = angle; }
    95             inline const Degree& getRotationRate() const
    96                 { return this->rotationRate_; }
    97 
    98             inline void setMomentum(const Degree& angle)
    99                 { this->momentum_ = angle; }
    100             inline void setMomentum(const Radian& angle)
    101                 { this->momentum_ = angle; }
    102             inline const Degree& getMomentum() const
    103                 { return this->momentum_; }
     53            inline void setPosition(const Vector3& position)
     54                { MobileEntity::setPosition(position); this->overwrite_position_ = this->getPosition(); }
     55            inline void setOrientation(const Quaternion& orientation)
     56                { MobileEntity::setOrientation(orientation); this->overwrite_orientation_ = this->getOrientation(); }
    10457
    10558        private:
     
    10861            void resynchronize();
    10962
    110             void overwritePosition();
    111             void overwriteOrientation();
     63            inline void processLinearVelocity()
     64                { this->setVelocity(this->linearVelocity_); }
     65            inline void processAngularVelocity()
     66                { this->setAngularVelocity(this->angularVelocity_); }
    11267
    113             Vector3 velocity_;
    114             Vector3 acceleration_;
    115             Vector3 rotationAxis_;
    116             Degree rotationRate_;
    117             Degree momentum_;
     68            inline void overwritePosition()
     69                { this->setPosition(this->overwrite_position_); }
     70            inline void overwriteOrientation()
     71                { this->setOrientation(this->overwrite_orientation_); }
    11872
    119             Vector3 overwrite_position_;
     73            Vector3    overwrite_position_;
    12074            Quaternion overwrite_orientation_;
     75
     76            Timer<MovableEntity> resynchronizeTimer_;
     77            Timer<MovableEntity>* continuousResynchroTimer_;
    12178    };
    12279}
  • code/trunk/src/orxonox/objects/worldentities/ParticleEmitter.cc

    r2171 r2662  
    3333
    3434#include "OrxonoxStableHeaders.h"
     35#include "ParticleEmitter.h"
    3536
    36 #include "ParticleEmitter.h"
     37#include <OgreParticleSystem.h>
    3738
    3839#include "tools/ParticleInterface.h"
     
    4647    CreateFactory(ParticleEmitter);
    4748
    48     ParticleEmitter::ParticleEmitter(BaseObject* creator) : PositionableEntity(creator)
     49    ParticleEmitter::ParticleEmitter(BaseObject* creator) : StaticEntity(creator)
    4950    {
    5051        RegisterObject(ParticleEmitter);
    5152
    52         if (!this->getScene() || !this->getScene()->getSceneManager())
    53             ThrowException(AbortLoading, "Can't create Camera, no scene or no scene manager given.");
     53        if (Core::showsGraphics() && (!this->getScene() || !this->getScene()->getSceneManager()))
     54            ThrowException(AbortLoading, "Can't create ParticleEmitter, no scene or no scene manager given.");
    5455
    5556        this->particles_ = 0;
     
    6263    {
    6364        if (this->isInitialized() && this->particles_)
     65        {
     66            this->detachOgreObject(this->particles_->getParticleSystem());
    6467            delete this->particles_;
     68        }
    6569    }
    6670
     
    7579    void ParticleEmitter::registerVariables()
    7680    {
    77         REGISTERSTRING(this->source_, direction::toclient, new NetworkCallback<ParticleEmitter>(this, &ParticleEmitter::sourceChanged));
    78         REGISTERDATA  (this->LOD_,    direction::toclient, new NetworkCallback<ParticleEmitter>(this, &ParticleEmitter::LODchanged));
     81        registerVariable(this->source_, variableDirection::toclient, new NetworkCallback<ParticleEmitter>(this, &ParticleEmitter::sourceChanged));
     82        registerVariable((int&)(this->LOD_),    variableDirection::toclient, new NetworkCallback<ParticleEmitter>(this, &ParticleEmitter::LODchanged));
    7983    }
    8084
     
    98102    {
    99103        if (this->particles_)
     104        {
    100105            delete this->particles_;
     106            this->particles_ = 0;
     107        }
    101108
    102         if (this->getScene() && this->getScene()->getSceneManager())
     109        if (Core::showsGraphics() && this->getScene() && this->getScene()->getSceneManager())
    103110        {
    104111            try
    105112            {
    106113                this->particles_ = new ParticleInterface(this->getScene()->getSceneManager(), this->source_, this->LOD_);
    107                 this->particles_->addToSceneNode(this->getNode());
     114                this->attachOgreObject(this->particles_->getParticleSystem());
    108115                this->particles_->setVisible(this->isVisible());
    109116                this->particles_->setEnabled(this->isActive());
     
    115122            }
    116123        }
    117         else
    118             this->particles_ = 0;
    119124    }
    120125
  • code/trunk/src/orxonox/objects/worldentities/ParticleEmitter.h

    r2087 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 #include "PositionableEntity.h"
     33#include "StaticEntity.h"
    3434
    3535namespace orxonox
    3636{
    37     class _OrxonoxExport ParticleEmitter : public PositionableEntity
     37    class _OrxonoxExport ParticleEmitter : public StaticEntity
    3838    {
    3939        public:
  • code/trunk/src/orxonox/objects/worldentities/ParticleSpawner.cc

  • code/trunk/src/orxonox/objects/worldentities/ParticleSpawner.h

  • code/trunk/src/orxonox/objects/worldentities/SpawnPoint.cc

    r2087 r2662  
    3838    CreateFactory(SpawnPoint);
    3939
    40     SpawnPoint::SpawnPoint(BaseObject* creator) : PositionableEntity(creator)
     40    SpawnPoint::SpawnPoint(BaseObject* creator) : StaticEntity(creator)
    4141    {
    4242        RegisterObject(SpawnPoint);
  • code/trunk/src/orxonox/objects/worldentities/SpawnPoint.h

    r2087 r2662  
    3434#include "core/Identifier.h"
    3535#include "core/Template.h"
    36 #include "PositionableEntity.h"
    3736#include "objects/worldentities/pawns/Pawn.h"
     37#include "objects/worldentities/StaticEntity.h"
    3838
    3939namespace orxonox
    4040{
    41     class _OrxonoxExport SpawnPoint : public PositionableEntity
     41    class _OrxonoxExport SpawnPoint : public StaticEntity
    4242    {
    4343        public:
  • code/trunk/src/orxonox/objects/worldentities/StaticEntity.cc

    • Property svn:mergeinfo changed (with no actual effect on merging)
  • code/trunk/src/orxonox/objects/worldentities/StaticEntity.h

    • Property svn:mergeinfo changed (with no actual effect on merging)
  • code/trunk/src/orxonox/objects/worldentities/WorldEntity.cc

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder (physics)
    2425 *   Co-authors:
    2526 *      ...
     
    3132
    3233#include <cassert>
     34#include <OgreSceneNode.h>
    3335#include <OgreSceneManager.h>
    34 
     36#include "BulletDynamics/Dynamics/btRigidBody.h"
     37
     38#include "util/Exception.h"
     39#include "util/Convert.h"
    3540#include "core/CoreIncludes.h"
    3641#include "core/XMLPort.h"
    37 #include "util/Convert.h"
    38 #include "util/Exception.h"
    3942
    4043#include "objects/Scene.h"
     44#include "objects/collisionshapes/WorldEntityCollisionShape.h"
    4145
    4246namespace orxonox
     
    4953    const Vector3 WorldEntity::UP    = Vector3::UNIT_Y;
    5054
     55    /**
     56    @brief
     57        Creates a new WorldEntity that may immediately be used.
     58        All the default values are being set here.
     59    */
    5160    WorldEntity::WorldEntity(BaseObject* creator) : BaseObject(creator), Synchronisable(creator)
    5261    {
     
    6473        this->node_->setOrientation(Quaternion::IDENTITY);
    6574
     75
     76        // Default behaviour does not include physics
     77        this->physicalBody_   = 0;
     78        this->bPhysicsActive_ = false;
     79        this->bPhysicsActiveSynchronised_    = false;
     80        this->bPhysicsActiveBeforeAttaching_ = false;
     81        this->collisionShape_ = new WorldEntityCollisionShape(this);
     82        this->collisionType_             = None;
     83        this->collisionTypeSynchronised_ = None;
     84        this->mass_           = 0;
     85        this->childrenMass_   = 0;
     86        // Using bullet default values
     87        this->restitution_    = 0;
     88        this->angularFactor_  = 1;
     89        this->linearDamping_  = 0;
     90        this->angularDamping_ = 0;
     91        this->friction_       = 0.5;
     92        this->bCollisionCallbackActive_ = false;
     93        this->bCollisionResponseActive_ = true;
     94
    6695        this->registerVariables();
    6796    }
    6897
     98    /**
     99    @brief
     100        Destroys the WorldEntity AND ALL its children with it.
     101    */
    69102    WorldEntity::~WorldEntity()
    70103    {
    71104        if (this->isInitialized())
    72105        {
     106            if (this->parent_)
     107                this->detachFromParent();
     108
     109            for (std::set<WorldEntity*>::const_iterator it = this->children_.begin(); it != this->children_.end(); )
     110                delete (*(it++));
     111
     112            if (this->physicalBody_)
     113            {
     114                this->deactivatePhysics();
     115                delete this->physicalBody_;
     116            }
     117            delete this->collisionShape_;
     118
    73119            this->node_->detachAllObjects();
    74             if (this->getScene()->getSceneManager())
    75                 this->getScene()->getSceneManager()->destroySceneNode(this->node_->getName());
     120            this->node_->removeAllChildren();
     121
     122            OrxAssert(this->getScene()->getSceneManager(), "No SceneManager defined in a WorldEntity.");
     123            this->getScene()->getSceneManager()->destroySceneNode(this->node_->getName());
    76124        }
    77125    }
     
    81129        SUPER(WorldEntity, XMLPort, xmlelement, mode);
    82130
    83         XMLPortParamTemplate(WorldEntity, "position", setPosition, getPosition, xmlelement, mode, const Vector3&);
     131        XMLPortParamTemplate(WorldEntity, "position",    setPosition,    getPosition,    xmlelement, mode, const Vector3&);
    84132        XMLPortParamTemplate(WorldEntity, "orientation", setOrientation, getOrientation, xmlelement, mode, const Quaternion&);
    85         XMLPortParamLoadOnly(WorldEntity, "lookat", lookAt_xmlport, xmlelement, mode);
    86         XMLPortParamLoadOnly(WorldEntity, "direction", setDirection_xmlport, xmlelement, mode);
    87         XMLPortParamLoadOnly(WorldEntity, "yaw", yaw_xmlport, xmlelement, mode);
    88         XMLPortParamLoadOnly(WorldEntity, "pitch", pitch_xmlport, xmlelement, mode);
    89         XMLPortParamLoadOnly(WorldEntity, "roll", roll_xmlport, xmlelement, mode);
    90         XMLPortParamTemplate(WorldEntity, "scale3D", setScale3D, getScale3D, xmlelement, mode, const Vector3&);
    91         XMLPortParam(WorldEntity, "scale", setScale, getScale, xmlelement, mode);
    92 
     133        XMLPortParamTemplate(WorldEntity, "scale3D",     setScale3D,     getScale3D,     xmlelement, mode, const Vector3&);
     134        XMLPortParam        (WorldEntity, "scale",       setScale,       getScale,       xmlelement, mode);
     135        XMLPortParamLoadOnly(WorldEntity, "lookat",      lookAt_xmlport,       xmlelement, mode);
     136        XMLPortParamLoadOnly(WorldEntity, "direction",   setDirection_xmlport, xmlelement, mode);
     137        XMLPortParamLoadOnly(WorldEntity, "yaw",         yaw_xmlport,          xmlelement, mode);
     138        XMLPortParamLoadOnly(WorldEntity, "pitch",       pitch_xmlport,        xmlelement, mode);
     139        XMLPortParamLoadOnly(WorldEntity, "roll",        roll_xmlport,         xmlelement, mode);
     140
     141        // Physics
     142        XMLPortParam(WorldEntity, "collisionType",     setCollisionTypeStr,  getCollisionTypeStr,  xmlelement, mode);
     143        XMLPortParam(WorldEntity, "collisionResponse", setCollisionResponse, hasCollisionResponse, xmlelement, mode);
     144        XMLPortParam(WorldEntity, "mass",              setMass,              getMass,              xmlelement, mode);
     145        XMLPortParam(WorldEntity, "restitution",       setRestitution,       getRestitution,       xmlelement, mode);
     146        XMLPortParam(WorldEntity, "angularFactor",     setAngularFactor,     getAngularFactor,     xmlelement, mode);
     147        XMLPortParam(WorldEntity, "linearDamping",     setLinearDamping,     getLinearDamping,     xmlelement, mode);
     148        XMLPortParam(WorldEntity, "angularDamping",    setAngularDamping,    getAngularDamping,    xmlelement, mode);
     149        XMLPortParam(WorldEntity, "friction",          setFriction,          getFriction,          xmlelement, mode);
     150
     151        // Other attached WorldEntities
    93152        XMLPortObject(WorldEntity, WorldEntity, "attached", attach, getAttachedObject, xmlelement, mode);
     153        // Attached collision shapes
     154        XMLPortObject(WorldEntity, CollisionShape, "collisionShapes", attachCollisionShape, getAttachedCollisionShape, xmlelement, mode);
    94155    }
    95156
    96157    void WorldEntity::registerVariables()
    97158    {
    98         REGISTERDATA(this->bActive_,  direction::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedActivity));
    99         REGISTERDATA(this->bVisible_, direction::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedVisibility));
    100 
    101         REGISTERDATA(this->getScale3D().x, direction::toclient);
    102         REGISTERDATA(this->getScale3D().y, direction::toclient);
    103         REGISTERDATA(this->getScale3D().z, direction::toclient);
    104 
    105         REGISTERDATA(this->parentID_, direction::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::updateParent));
    106     }
    107 
    108     void WorldEntity::updateParent()
     159        registerVariable(this->mainStateName_,  variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedMainState));
     160
     161        registerVariable(this->bActive_,        variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedActivity));
     162        registerVariable(this->bVisible_,       variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedVisibility));
     163
     164        registerVariable(this->getScale3D(),    variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::scaleChanged));
     165
     166        // Physics stuff
     167        registerVariable(this->mass_,           variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::massChanged));
     168        registerVariable(this->restitution_,    variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::restitutionChanged));
     169        registerVariable(this->angularFactor_,  variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::angularFactorChanged));
     170        registerVariable(this->linearDamping_,  variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::linearDampingChanged));
     171        registerVariable(this->angularDamping_, variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::angularDampingChanged));
     172        registerVariable(this->friction_,       variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::frictionChanged));
     173        registerVariable(this->bCollisionCallbackActive_,
     174                                                variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionCallbackActivityChanged));
     175        registerVariable(this->bCollisionResponseActive_,
     176                                                variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionResponseActivityChanged));
     177        registerVariable((int&)this->collisionTypeSynchronised_,
     178                                                variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::collisionTypeChanged));
     179        registerVariable(this->bPhysicsActiveSynchronised_,
     180                                                variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::physicsActivityChanged));
     181
     182        // Attach to parent if necessary
     183        registerVariable(this->parentID_,       variableDirection::toclient, new NetworkCallback<WorldEntity>(this, &WorldEntity::parentChanged));
     184    }
     185
     186    /**
     187    @brief
     188        Network function that object this instance to its correct parent.
     189    */
     190    void WorldEntity::parentChanged()
    109191    {
    110192        if (this->parentID_ != OBJECTID_UNKNOWN)
     
    116198    }
    117199
     200    /**
     201    @brief
     202        Attaches this object to a parent SceneNode.
     203    @Remarks
     204        Only use this method if you know exactly what you're doing!
     205        Normally, attaching works internally by attaching WE's.
     206    */
     207    void WorldEntity::attachToNode(Ogre::SceneNode* node)
     208    {
     209        Ogre::Node* parent = this->node_->getParent();
     210        if (parent)
     211            parent->removeChild(this->node_);
     212        node->addChild(this->node_);
     213    }
     214
     215    /**
     216    @brief
     217        Detaches this object from a parent SceneNode.
     218    @Remarks
     219        Only use this method if you know exactly what you're doing!
     220        Normally, attaching works internally by attaching WE's.
     221    */
     222    void WorldEntity::detachFromNode(Ogre::SceneNode* node)
     223    {
     224        node->removeChild(this->node_);
     225//        this->getScene()->getRootSceneNode()->addChild(this->node_);
     226    }
     227
     228    /**
     229    @brief
     230        Network callback for the collision type. Only change the type if it was valid.
     231    */
     232    void WorldEntity::collisionTypeChanged()
     233    {
     234        if (this->collisionTypeSynchronised_ != Dynamic &&
     235            this->collisionTypeSynchronised_ != Kinematic &&
     236            this->collisionTypeSynchronised_ != Static &&
     237            this->collisionTypeSynchronised_ != None)
     238        {
     239            CCOUT(1) << "Error when collsion Type was received over network. Unknown enum value:" << this->collisionTypeSynchronised_ << std::endl;
     240        }
     241        else if (this->collisionTypeSynchronised_ != collisionType_)
     242        {
     243            if (this->parent_)
     244                CCOUT(2) << "Warning: Network connection tried to set the collision type of an attached WE. Ignoring." << std::endl;
     245            else
     246                this->setCollisionType(this->collisionTypeSynchronised_);
     247        }
     248    }
     249
     250    //! Network callback for this->bPhysicsActive_
     251    void WorldEntity::physicsActivityChanged()
     252    {
     253        if (this->bPhysicsActiveSynchronised_)
     254            this->activatePhysics();
     255        else
     256            this->deactivatePhysics();
     257    }
     258
     259    //! Function sets whether Bullet should issue a callback on collisions
     260    void WorldEntity::collisionCallbackActivityChanged()
     261    {
     262        if (this->hasPhysics())
     263        {
     264            if (this->bCollisionCallbackActive_)
     265                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() |
     266                    btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
     267            else
     268                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() &
     269                    ~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
     270        }
     271    }
     272
     273    //! Function sets whether Bullet should react itself to a collision
     274    void WorldEntity::collisionResponseActivityChanged()
     275    {
     276        if (this->hasPhysics())
     277        {
     278            if (this->bCollisionResponseActive_)
     279                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() &
     280                    ~btCollisionObject::CF_NO_CONTACT_RESPONSE);
     281            else
     282                this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() |
     283                    btCollisionObject::CF_NO_CONTACT_RESPONSE);
     284        }
     285    }
     286
     287    /**
     288    @brief
     289        Attaches a child WorldEntity to this object. This calls notifyBeingAttached()
     290        of the child WE.
     291    @Note
     292        The collision shape of the child object gets attached nevertheless. That also means
     293        that you can change the collision shape of the child and it correctly cascadeds the changes to this instance.
     294        Be aware of this implication: When implementing attaching of kinematic objects to others, you have to change
     295        this behaviour because you then might not want to merge the collision shapes.
     296    */
    118297    void WorldEntity::attach(WorldEntity* object)
    119298    {
    120         if (object->getParent())
    121             object->detachFromParent();
    122         else
    123         {
    124             Ogre::Node* parent = object->node_->getParent();
    125             if (parent)
    126                 parent->removeChild(object->node_);
    127         }
    128 
    129         this->node_->addChild(object->node_);
     299        if (object == this)
     300        {
     301            COUT(2) << "Warning: Can't attach a WorldEntity to itself." << std::endl;
     302            return;
     303        }
     304
     305        if (!object->notifyBeingAttached(this))
     306            return;
     307
     308        this->attachNode(object->node_);
    130309        this->children_.insert(object);
    131         object->parent_ = this;
    132         object->parentID_ = this->getObjectID();
    133     }
    134 
     310
     311        this->attachCollisionShape(object->collisionShape_);
     312        // mass
     313        this->childrenMass_ += object->getMass();
     314        recalculateMassProps();
     315    }
     316
     317    /**
     318    @brief
     319        Function gets called when this object is being attached to a new parent.
     320
     321        This operation is only allowed if the collision types "like" each other.
     322        - You cannot a attach a non physical object to a physical one.
     323        - Dynamic object can NOT be attached at all.
     324        - It is also not possible to attach a kinematic to a dynamic one.
     325        - Attaching of kinematic objects otherwise is not yet supported.
     326    */
     327    bool WorldEntity::notifyBeingAttached(WorldEntity* newParent)
     328    {
     329        // check first whether attaching is even allowed
     330        if (this->hasPhysics())
     331        {
     332            if (!newParent->hasPhysics())
     333            {
     334                COUT(2) << "Warning: Cannot attach a physical object to a non physical one." << std::endl;
     335                return false;
     336            }
     337            else if (this->isDynamic())
     338            {
     339                COUT(2) << "Warning: Cannot attach a dynamic object to a WorldEntity." << std::endl;
     340                return false;
     341            }
     342            else if (this->isKinematic() && newParent->isDynamic())
     343            {
     344                COUT(2) << "Warning: Cannot attach a kinematic object to a dynamic one." << std::endl;
     345                return false;
     346            }
     347            else if (this->isKinematic())
     348            {
     349                COUT(2) << "Warning: Cannot attach a kinematic object to a static or kinematic one: Not yet implemented." << std::endl;
     350                return false;
     351            }
     352        }
     353
     354        if (this->isPhysicsActive())
     355            this->bPhysicsActiveBeforeAttaching_ = true;
     356        this->deactivatePhysics();
     357
     358        if (this->parent_)
     359            this->detachFromParent();
     360
     361        this->parent_ = newParent;
     362        this->parentID_ = newParent->getObjectID();
     363
     364        // apply transform to collision shape
     365        this->collisionShape_->setPosition(this->getPosition());
     366        this->collisionShape_->setOrientation(this->getOrientation());
     367        // TODO: Scale
     368       
     369        return true;
     370    }
     371
     372    /**
     373    @brief
     374        Detaches a child WorldEntity from this instance.
     375    */
    135376    void WorldEntity::detach(WorldEntity* object)
    136377    {
    137         this->node_->removeChild(object->node_);
     378        if (this->children_.find(object) == this->children_.end())
     379        {
     380            CCOUT(2) << "Warning: Cannot detach an object that is not a child." << std::endl;
     381            return;
     382        }
     383
     384        // collision shapes
     385        this->detachCollisionShape(object->collisionShape_);
     386
     387        // mass
     388        if (object->getMass() > 0.0f)
     389        {
     390            this->childrenMass_ -= object->getMass();
     391            recalculateMassProps();
     392        }
     393
     394        this->detachNode(object->node_);
    138395        this->children_.erase(object);
    139         object->parent_ = 0;
    140         object->parentID_ = OBJECTID_UNKNOWN;
    141 
    142 //        this->getScene()->getRootSceneNode()->addChild(object->node_);
    143     }
    144 
    145     WorldEntity* WorldEntity::getAttachedObject(unsigned int index) const
     396
     397        object->notifyDetached();
     398    }
     399
     400    /**
     401    @brief
     402        Function gets called when the object has been detached from its parent.
     403    */
     404    void WorldEntity::notifyDetached()
     405    {
     406        this->parent_ = 0;
     407        this->parentID_ = OBJECTID_UNKNOWN;
     408
     409        // reset orientation of the collisionShape (cannot be set within a WE usually)
     410        this->collisionShape_->setPosition(Vector3::ZERO);
     411        this->collisionShape_->setOrientation(Quaternion::IDENTITY);
     412        // TODO: Scale
     413
     414        if (this->bPhysicsActiveBeforeAttaching_)
     415        {
     416            this->activatePhysics();
     417            this->bPhysicsActiveBeforeAttaching_ = false;
     418        }
     419    }
     420
     421    //! Returns an attached object (merely for XMLPort).
     422    WorldEntity* WorldEntity::getAttachedObject(unsigned int index)
    146423    {
    147424        unsigned int i = 0;
     
    154431        return 0;
    155432    }
     433
     434    //! Attaches an Ogre::SceneNode to this WorldEntity.
     435    void WorldEntity::attachNode(Ogre::SceneNode* node)
     436    {
     437        Ogre::Node* parent = node->getParent();
     438        if (parent)
     439            parent->removeChild(node);
     440        this->node_->addChild(node);
     441    }
     442
     443    //! Detaches an Ogre::SceneNode from this WorldEntity.
     444    void WorldEntity::detachNode(Ogre::SceneNode* node)
     445    {
     446        this->node_->removeChild(node);
     447//        this->getScene()->getRootSceneNode()->addChild(node);
     448    }
     449
     450    //! Attaches an Ogre::MovableObject to this WorldEntity.
     451    void WorldEntity::attachOgreObject(Ogre::MovableObject* object)
     452    {
     453        this->node_->attachObject(object);
     454    }
     455
     456    //! Detaches an Ogre::MovableObject from this WorldEntity.
     457    void WorldEntity::detachOgreObject(Ogre::MovableObject* object)
     458    {
     459        this->node_->detachObject(object);
     460    }
     461
     462    //! Detaches an Ogre::MovableObject (by string) from this WorldEntity.
     463    Ogre::MovableObject* WorldEntity::detachOgreObject(const Ogre::String& name)
     464    {
     465        return this->node_->detachObject(name);
     466    }
     467
     468    //! Attaches a collision Shape to this object (delegated to the internal CompoundCollisionShape)
     469    void WorldEntity::attachCollisionShape(CollisionShape* shape)
     470    {
     471        this->collisionShape_->attach(shape);
     472        // Note: this->collisionShape_ already notifies us of any changes.
     473    }
     474
     475    //! Detaches a collision Shape from this object (delegated to the internal CompoundCollisionShape)
     476    void WorldEntity::detachCollisionShape(CollisionShape* shape)
     477    {
     478        // Note: The collision shapes may not be detached with this function!
     479        this->collisionShape_->detach(shape);
     480        // Note: this->collisionShape_ already notifies us of any changes.
     481    }
     482
     483    //! Returns an attached collision Shape of this object (delegated to the internal CompoundCollisionShape)
     484    CollisionShape* WorldEntity::getAttachedCollisionShape(unsigned int index)
     485    {
     486        return this->collisionShape_->getAttachedShape(index);
     487    }
     488
     489    // Note: These functions are placed in WorldEntity.h as inline functions for the release build.
     490#ifndef _NDEBUG
     491    const Vector3& WorldEntity::getPosition() const
     492    {
     493        return this->node_->getPosition();
     494    }
     495
     496    const Quaternion& WorldEntity::getOrientation() const
     497    {
     498        return this->node_->getOrientation();
     499    }
     500
     501    const Vector3& WorldEntity::getScale3D() const
     502    {
     503        return this->node_->getScale();
     504    }
     505#endif
     506
     507    //! Returns the position relative to the root space
     508    const Vector3& WorldEntity::getWorldPosition() const
     509    {
     510        return this->node_->_getDerivedPosition();
     511    }
     512
     513    //! Returns the orientation relative to the root space
     514    const Quaternion& WorldEntity::getWorldOrientation() const
     515    {
     516        return this->node_->_getDerivedOrientation();
     517    }
     518
     519    //! Returns the scaling applied relative to the root space in 3 coordinates
     520    const Vector3& WorldEntity::getWorldScale3D() const
     521    {
     522        return this->node_->_getDerivedScale();
     523    }
     524
     525    /**
     526    @brief
     527        Returns the scaling applied relative to the root space in 3 coordinates
     528    @return
     529        Returns the scaling if it is uniform, 1.0f otherwise.
     530    */
     531    float WorldEntity::getWorldScale() const
     532    {
     533        Vector3 scale = this->getWorldScale3D();
     534        return (scale.x == scale.y && scale.x == scale.z) ? scale.x : 1;
     535    }
     536
     537    /**
     538    @brief
     539        Sets the three dimensional scaling of this object.
     540    @Note
     541        Scaling physical objects has not yet been implemented and is therefore forbidden.
     542    */
     543    void WorldEntity::setScale3D(const Vector3& scale)
     544    {
     545/*
     546HACK HACK HACK
     547        if (bScalePhysics && this->hasPhysics() && scale != Vector3::UNIT_SCALE)
     548        {
     549            CCOUT(2) << "Warning: Cannot set the scale of a physical object: Not yet implemented. Ignoring scaling." << std::endl;
     550            return;
     551        }
     552HACK HACK HACK
     553*/
     554        this->node_->setScale(scale);
     555
     556        this->changedScale();
     557    }
     558
     559    /**
     560    @brief
     561        Translates this WorldEntity by a vector.
     562    @param relativeTo
     563        @see TransformSpace::Enum
     564    */
     565    void WorldEntity::translate(const Vector3& distance, TransformSpace::Enum relativeTo)
     566    {
     567        switch (relativeTo)
     568        {
     569        case TransformSpace::Local:
     570            // position is relative to parent so transform downwards
     571            this->setPosition(this->getPosition() + this->getOrientation() * distance);
     572            break;
     573        case TransformSpace::Parent:
     574            this->setPosition(this->getPosition() + distance);
     575            break;
     576        case TransformSpace::World:
     577            // position is relative to parent so transform upwards
     578            if (this->node_->getParent())
     579                setPosition(getPosition() + (node_->getParent()->_getDerivedOrientation().Inverse() * distance)
     580                    / node_->getParent()->_getDerivedScale());
     581            else
     582                this->setPosition(this->getPosition() + distance);
     583            break;
     584        }
     585    }
     586
     587    /**
     588    @brief
     589        Rotates this WorldEntity by a quaternion.
     590    @param relativeTo
     591        @see TransformSpace::Enum
     592    */
     593    void WorldEntity::rotate(const Quaternion& rotation, TransformSpace::Enum relativeTo)
     594    {
     595        switch(relativeTo)
     596        {
     597        case TransformSpace::Local:
     598            this->setOrientation(this->getOrientation() * rotation);
     599            break;
     600        case TransformSpace::Parent:
     601            // Rotations are normally relative to local axes, transform up
     602            this->setOrientation(rotation * this->getOrientation());
     603            break;
     604        case TransformSpace::World:
     605            // Rotations are normally relative to local axes, transform up
     606            this->setOrientation(this->getOrientation() * this->getWorldOrientation().Inverse()
     607                * rotation * this->getWorldOrientation());
     608            break;
     609        }
     610    }
     611
     612    /**
     613    @brief
     614        Makes this WorldEntity look a specific target location.
     615    @param relativeTo
     616        @see TransformSpace::Enum
     617    @param localDirectionVector
     618        The vector which normally describes the natural direction of the object, usually -Z.
     619    */
     620    void WorldEntity::lookAt(const Vector3& target, TransformSpace::Enum relativeTo, const Vector3& localDirectionVector)
     621    {
     622        Vector3 origin;
     623        switch (relativeTo)
     624        {
     625        case TransformSpace::Local:
     626            origin = Vector3::ZERO;
     627            break;
     628        case TransformSpace::Parent:
     629            origin = this->getPosition();
     630            break;
     631        case TransformSpace::World:
     632            origin = this->getWorldPosition();
     633            break;
     634        }
     635        this->setDirection(target - origin, relativeTo, localDirectionVector);
     636    }
     637
     638    /**
     639    @brief
     640        Makes this WorldEntity look in specific direction.
     641    @param relativeTo
     642        @see TransformSpace::Enum
     643    @param localDirectionVector
     644        The vector which normally describes the natural direction of the object, usually -Z.
     645    */
     646    void WorldEntity::setDirection(const Vector3& direction, TransformSpace::Enum relativeTo, const Vector3& localDirectionVector)
     647    {
     648        Quaternion savedOrientation(this->getOrientation());
     649        Ogre::Node::TransformSpace ogreRelativeTo;
     650        switch (relativeTo)
     651        {
     652        case TransformSpace::Local:
     653            ogreRelativeTo = Ogre::Node::TS_LOCAL; break;
     654        case TransformSpace::Parent:
     655            ogreRelativeTo = Ogre::Node::TS_PARENT; break;
     656        case TransformSpace::World:
     657            ogreRelativeTo = Ogre::Node::TS_WORLD; break;
     658        }
     659        this->node_->setDirection(direction, ogreRelativeTo, localDirectionVector);
     660        Quaternion newOrientation(this->node_->getOrientation());
     661        this->node_->setOrientation(savedOrientation);
     662        this->setOrientation(newOrientation);
     663    }
     664
     665    //! Activates physics if the CollisionType is not None.
     666    void WorldEntity::activatePhysics()
     667    {
     668        if (this->isActive() && this->hasPhysics() && !this->isPhysicsActive() && !this->parent_)
     669        {
     670            this->getScene()->addPhysicalObject(this);
     671            this->bPhysicsActive_ = true;
     672            this->bPhysicsActiveSynchronised_ = true;
     673        }
     674    }
     675
     676    //! Deactivates physics but the CollisionType does not change.
     677    void WorldEntity::deactivatePhysics()
     678    {
     679        if (this->isPhysicsActive())
     680        {
     681            this->getScene()->removePhysicalObject(this);
     682            this->bPhysicsActive_ = false;
     683            this->bPhysicsActiveSynchronised_ = false;
     684        }
     685    }
     686
     687    //! Tells whether the object has already been added to the Bullet physics World.
     688    bool WorldEntity::addedToPhysicalWorld() const
     689    {
     690        return this->physicalBody_ && this->physicalBody_->isInWorld();
     691    }
     692
     693    /**
     694    @brief
     695        Sets the CollisionType. This alters the object significantly! @see CollisionType.
     696    @Note
     697        Operation does not work on attached WorldEntities.
     698    */
     699    void WorldEntity::setCollisionType(CollisionType type)
     700    {
     701        if (this->collisionType_ == type)
     702            return;
     703
     704        // If we are already attached to a parent, this would be a bad idea..
     705        if (this->parent_)
     706        {
     707            CCOUT(2) << "Warning: Cannot set the collision type of a WorldEntity with a parent." << std::endl;
     708            return;
     709        }
     710
     711        // Check for type legality. Could be StaticEntity or MobileEntity.
     712        if (!this->isCollisionTypeLegal(type))
     713            return;
     714
     715        if (this->isPhysicsActive())
     716            this->deactivatePhysics();
     717
     718        bool bReactivatePhysics = true;
     719        if (this->hasPhysics() && !this->isPhysicsActive())
     720            bReactivatePhysics = false;
     721
     722        // Check whether we have to create or destroy.
     723        if (type != None && this->collisionType_ == None)
     724        {
     725/*
     726HACK HACK HACK
     727            // Check whether there was some scaling applied.
     728            if (!this->node_->getScale().positionEquals(Vector3(1, 1, 1), 0.001))
     729            {
     730                CCOUT(2) << "Warning: Cannot create a physical body if there is scaling applied to the node: Not yet implemented." << std::endl;
     731                return;
     732            }
     733HACK HACK HACK
     734*/
     735            // Create new rigid body
     736            btRigidBody::btRigidBodyConstructionInfo bodyConstructionInfo(0, this, this->collisionShape_->getCollisionShape());
     737            this->physicalBody_ = new btRigidBody(bodyConstructionInfo);
     738            this->physicalBody_->setUserPointer(this);
     739            this->physicalBody_->setActivationState(DISABLE_DEACTIVATION);
     740        }
     741        else if (type == None && this->collisionType_ != None)
     742        {
     743            // Destroy rigid body
     744            assert(this->physicalBody_);
     745            deactivatePhysics();
     746            delete this->physicalBody_;
     747            this->physicalBody_ = 0;
     748            this->collisionType_ = None;
     749            this->collisionTypeSynchronised_ = None;
     750            return;
     751        }
     752
     753        // Change type
     754        switch (type)
     755        {
     756        case Dynamic:
     757            this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() & !(btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT));
     758            break;
     759        case Kinematic:
     760            this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() & !btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT);
     761            break;
     762        case Static:
     763            this->physicalBody_->setCollisionFlags(this->physicalBody_->getCollisionFlags() & !btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT);
     764            break;
     765        case None:
     766            assert(false); // Doesn't happen
     767            return;
     768        }
     769        this->collisionType_ = type;
     770        this->collisionTypeSynchronised_ = type;
     771
     772        // update mass and inertia tensor
     773        recalculateMassProps();
     774        internalSetPhysicsProps();
     775        collisionCallbackActivityChanged();
     776        collisionResponseActivityChanged();
     777        if (bReactivatePhysics)
     778            activatePhysics();
     779    }
     780
     781    //! Sets the CollisionType by string (used for the XMLPort)
     782    void WorldEntity::setCollisionTypeStr(const std::string& typeStr)
     783    {
     784        std::string typeStrLower = getLowercase(typeStr);
     785        CollisionType type;
     786        if (typeStrLower == "dynamic")
     787            type = Dynamic;
     788        else if (typeStrLower == "static")
     789            type = Static;
     790        else if (typeStrLower == "kinematic")
     791            type = Kinematic;
     792        else if (typeStrLower == "none")
     793            type = None;
     794        else
     795            ThrowException(ParseError, std::string("Attempting to set an unknown collision type: '") + typeStr + "'.");
     796        this->setCollisionType(type);
     797    }
     798
     799    //! Gets the CollisionType by string (used for the XMLPort)
     800    std::string WorldEntity::getCollisionTypeStr() const
     801    {
     802        switch (this->getCollisionType())
     803        {
     804            case Dynamic:
     805                return "dynamic";
     806            case Kinematic:
     807                return "kinematic";
     808            case Static:
     809                return "static";
     810            case None:
     811                return "none";
     812            default:
     813                assert(false);
     814                return "";
     815        }
     816    }
     817
     818    /**
     819    @brief
     820        Recalculates the accumulated child mass and calls recalculateMassProps()
     821        and notifies the parent of the change.
     822    @Note
     823        Called by a child WE
     824    */
     825    void WorldEntity::notifyChildMassChanged()
     826    {
     827        // Note: CollisionShape changes of a child get handled over the internal CompoundCollisionShape already
     828        // Recalculate mass
     829        this->childrenMass_ = 0.0f;
     830        for (std::set<WorldEntity*>::const_iterator it = this->children_.begin(); it != this->children_.end(); ++it)
     831            this->childrenMass_ += (*it)->getMass();
     832        recalculateMassProps();
     833        // Notify parent WE
     834        if (this->parent_)
     835            parent_->notifyChildMassChanged();
     836    }
     837
     838    /**
     839    @brief
     840        Undertakes the necessary steps to change the collision shape in Bullet, even at runtime.
     841    @Note
     842        - called by this->collisionShape_
     843        - May have a REALLY big overhead when called continuously at runtime, because then we need
     844          to remove the physical body from Bullet and add it again.
     845    */
     846    void WorldEntity::notifyCollisionShapeChanged()
     847    {
     848        if (hasPhysics())
     849        {
     850            // Bullet doesn't like sudden changes of the collision shape, so we remove and add it again
     851            if (this->addedToPhysicalWorld())
     852            {
     853                this->deactivatePhysics();
     854                this->physicalBody_->setCollisionShape(this->collisionShape_->getCollisionShape());
     855                this->activatePhysics();
     856            }
     857            else
     858                this->physicalBody_->setCollisionShape(this->collisionShape_->getCollisionShape());
     859        }
     860        recalculateMassProps();
     861    }
     862
     863    //! Updates all mass dependent parameters (mass, inertia tensor and child mass)
     864    void WorldEntity::recalculateMassProps()
     865    {
     866        // Store local inertia for faster access. Evaluates to (0,0,0) if there is no collision shape.
     867        float totalMass = this->mass_ + this->childrenMass_;
     868        this->collisionShape_->calculateLocalInertia(totalMass, this->localInertia_);
     869        if (this->hasPhysics())
     870        {
     871            if (this->isStatic())
     872            {
     873                // Just set everything to zero
     874                this->physicalBody_->setMassProps(0.0f, btVector3(0, 0, 0));
     875            }
     876            else if ((this->mass_ + this->childrenMass_) == 0.0f)
     877            {
     878                // Use default values to avoid very large or very small values
     879                CCOUT(4) << "Warning: Setting the internal physical mass to 1.0 because mass_ is 0.0" << std::endl;
     880                btVector3 inertia(0, 0, 0);
     881                this->collisionShape_->calculateLocalInertia(1.0f, inertia);
     882                this->physicalBody_->setMassProps(1.0f, inertia);
     883            }
     884            else
     885            {
     886                this->physicalBody_->setMassProps(totalMass, this->localInertia_);
     887            }
     888        }
     889    }
     890
     891    //! Copies our own parameters for restitution, angular factor, dampings and friction to the bullet rigid body.
     892    void WorldEntity::internalSetPhysicsProps()
     893    {
     894        if (this->hasPhysics())
     895        {
     896            this->physicalBody_->setRestitution(this->restitution_);
     897            this->physicalBody_->setAngularFactor(this->angularFactor_);
     898            this->physicalBody_->setDamping(this->linearDamping_, this->angularDamping_);
     899            this->physicalBody_->setFriction(this->friction_);
     900        }
     901    }
    156902}
  • code/trunk/src/orxonox/objects/worldentities/WorldEntity.h

    r2171 r2662  
    2222 *   Author:
    2323 *      Fabian 'x3n' Landau
     24 *      Reto Grieder (physics)
    2425 *   Co-authors:
    2526 *      ...
     
    3233#include "OrxonoxPrereqs.h"
    3334
    34 #define OGRE_FORCE_ANGLE_TYPES
    35 
     35#ifdef _NDEBUG
    3636#include <OgreSceneNode.h>
    37 
    38 #include "network/Synchronisable.h"
     37#else
     38#include <OgrePrerequisites.h>
     39#endif
     40#include "LinearMath/btMotionState.h"
     41
     42#include "util/Math.h"
    3943#include "core/BaseObject.h"
    40 #include "util/Math.h"
     44#include "network/synchronisable/Synchronisable.h"
    4145
    4246namespace orxonox
    4347{
    44     class _OrxonoxExport WorldEntity : public BaseObject, public Synchronisable
     48    /**
     49    @brief
     50        The WorldEntity represents everything that can be put in a Scene at a certain location.
     51
     52        It is supposed to be the base class of everything you would call an 'object' in a Scene.
     53        The class itself is abstract which means you cannot use it directly. You may use StaticEntity
     54        as the simplest derivative or (derived from MobileEntity) MovableEntity and ControllableEntity
     55        as more advanced ones.
     56
     57        The basic task of the WorldEntity is provide a location, a direction and a scaling and the possibility
     58        to create an entire hierarchy of derivated objects.
     59        It is also the basis for the physics interface to the Bullet physics engine.
     60        Every WorldEntity can have a specific collision type: @see CollisionType
     61        This would then imply that every scene object could have any collision type. To limit this, you can always
     62        override this->isCollisionTypeLegal(CollisionType). Return false if the collision type is not supported
     63        for a specific object.
     64        There is also support for attaching WorldEntities with physics to each other. Currently, the collision shape
     65        of both objects simply get merged into one larger shape (for static collision type).
     66        The phyiscal body that is internally stored and administrated has the following supported properties:
     67        - Restitution, angular factor, linear damping, angular damping, fricition, mass and collision shape.
     68        You can get more information at the corresponding set function.
     69
     70        Collision shapes: These are controlled by the internal WorldEntityCollisionShape. @see WorldEntityCollisionShape.
     71    */
     72    class _OrxonoxExport WorldEntity : public BaseObject, public Synchronisable, public btMotionState
    4573    {
     74        friend class Scene;
     75
    4676        public:
    4777            WorldEntity(BaseObject* creator);
     
    5181            void registerVariables();
    5282
    53             inline Ogre::SceneNode* getNode() const
     83            inline const Ogre::SceneNode* getNode() const
    5484                { return this->node_; }
    5585
     
    6494            inline void setPosition(float x, float y, float z)
    6595                { this->setPosition(Vector3(x, y, z)); }
    66             inline const Vector3& getPosition() const
    67                 { return this->node_->getPosition(); }
    68             inline const Vector3& getWorldPosition() const
    69                 { return this->node_->getWorldPosition(); }
    70 
    71             virtual void translate(const Vector3& distance, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL) = 0;
    72             inline void translate(float x, float y, float z, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
     96            const Vector3& getPosition() const;
     97            const Vector3& getWorldPosition() const;
     98
     99            void translate(const Vector3& distance, TransformSpace::Enum relativeTo = TransformSpace::Parent);
     100            inline void translate(float x, float y, float z, TransformSpace::Enum relativeTo = TransformSpace::Parent)
    73101                { this->translate(Vector3(x, y, z), relativeTo); }
     102
     103            virtual inline const Vector3& getVelocity() const
     104                { return Vector3::ZERO; }
    74105
    75106            virtual void setOrientation(const Quaternion& orientation) = 0;
     
    80111            inline void setOrientation(const Vector3& axis, const Degree& angle)
    81112                { this->setOrientation(Quaternion(angle, axis)); }
    82             inline const Quaternion& getOrientation() const
    83                 { return this->node_->getOrientation(); }
    84             inline const Quaternion& getWorldOrientation() const
    85                 { return this->node_->getWorldOrientation(); }
    86 
    87             virtual void rotate(const Quaternion& rotation, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL) = 0;
    88             inline void rotate(const Vector3& axis, const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
     113            const Quaternion& getOrientation() const;
     114            const Quaternion& getWorldOrientation() const;
     115
     116            void rotate(const Quaternion& rotation, TransformSpace::Enum relativeTo = TransformSpace::Local);
     117            inline void rotate(const Vector3& axis, const Degree& angle, TransformSpace::Enum relativeTo = TransformSpace::Local)
    89118                { this->rotate(Quaternion(angle, axis), relativeTo); }
    90             inline void rotate(const Vector3& axis, const Radian& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
    91                 { this->rotate(Quaternion(angle, axis), relativeTo); }
    92 
    93             virtual void yaw(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL) = 0;
    94             inline void yaw(const Radian& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
    95                 { this->yaw(Degree(angle), relativeTo); }
    96             virtual void pitch(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL) = 0;
    97             inline void pitch(const Radian& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
    98                 { this->pitch(Degree(angle), relativeTo); }
    99             virtual void roll(const Degree& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL) = 0;
    100             inline void roll(const Radian& angle, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL)
    101                 { this->roll(Degree(angle), relativeTo); }
    102 
    103             virtual void lookAt(const Vector3& target, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z) = 0;
    104             virtual void setDirection(const Vector3& direction, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z) = 0;
    105             inline void setDirection(float x, float y, float z, Ogre::Node::TransformSpace relativeTo = Ogre::Node::TS_LOCAL, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z)
     119
     120            inline void yaw(const Degree& angle, TransformSpace::Enum relativeTo = TransformSpace::Local)
     121                { this->rotate(Quaternion(angle, Vector3::UNIT_Y), relativeTo); }
     122            inline void pitch(const Degree& angle, TransformSpace::Enum relativeTo = TransformSpace::Local)
     123                { this->rotate(Quaternion(angle, Vector3::UNIT_X), relativeTo); }
     124            inline void roll(const Degree& angle, TransformSpace::Enum relativeTo = TransformSpace::Local)
     125                { this->rotate(Quaternion(angle, Vector3::UNIT_Z), relativeTo); }
     126
     127            void lookAt(const Vector3& target, TransformSpace::Enum relativeTo = TransformSpace::Parent, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
     128            void setDirection(const Vector3& direction, TransformSpace::Enum relativeTo = TransformSpace::Local, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z);
     129            inline void setDirection(float x, float y, float z, TransformSpace::Enum relativeTo = TransformSpace::Local, const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z)
    106130                { this->setDirection(Vector3(x, y, z), relativeTo, localDirectionVector); }
    107131
    108             inline void setScale3D(const Vector3& scale)
    109                 { this->node_->setScale(scale); }
     132            virtual void setScale3D(const Vector3& scale);
    110133            inline void setScale3D(float x, float y, float z)
    111                 { this->node_->setScale(x, y, z); }
    112             inline const Vector3& getScale3D(void) const
    113                 { return this->node_->getScale(); }
     134                { this->setScale3D(Vector3(x, y, z)); }
     135            const Vector3& getScale3D(void) const;
     136            const Vector3& getWorldScale3D() const;
    114137
    115138            inline void setScale(float scale)
    116                 { this->node_->setScale(scale, scale, scale); }
     139                { this->setScale3D(scale, scale, scale); }
    117140            inline float getScale() const
    118141                { Vector3 scale = this->getScale3D(); return (scale.x == scale.y && scale.x == scale.z) ? scale.x : 1; }
     142            float getWorldScale() const;
    119143
    120144            inline void scale3D(const Vector3& scale)
    121                 { this->node_->scale(scale); }
     145                { this->setScale3D(this->getScale3D() * scale); }
    122146            inline void scale3D(float x, float y, float z)
    123                 { this->node_->scale(x, y, z); }
     147                { this->scale3D(Vector3(x, y, z)); }
    124148            inline void scale(float scale)
    125                 { this->node_->scale(scale, scale, scale); }
     149                { this->scale3D(scale, scale, scale); }
     150
     151            virtual void changedScale() {}
    126152
    127153            void attach(WorldEntity* object);
    128154            void detach(WorldEntity* object);
    129             WorldEntity* getAttachedObject(unsigned int index) const;
     155            WorldEntity* getAttachedObject(unsigned int index);
    130156            inline const std::set<WorldEntity*>& getAttachedObjects() const
    131157                { return this->children_; }
     158
     159            void attachOgreObject(Ogre::MovableObject* object);
     160            void detachOgreObject(Ogre::MovableObject* object);
     161            Ogre::MovableObject* detachOgreObject(const Ogre::String& name);
    132162
    133163            inline void attachToParent(WorldEntity* parent)
     
    138168                { return this->parent_; }
    139169
     170            void attachNode(Ogre::SceneNode* node);
     171            void detachNode(Ogre::SceneNode* node);
     172            void attachToNode(Ogre::SceneNode* node);
     173            void detachFromNode(Ogre::SceneNode* node);
     174
     175            void notifyChildPropsChanged();
     176
    140177        protected:
    141178            Ogre::SceneNode* node_;
    142179
    143180        private:
    144             void updateParent();
    145 
    146181            inline void lookAt_xmlport(const Vector3& target)
    147182                { this->lookAt(target); }
     
    155190                { this->roll(angle); }
    156191
     192            // network callbacks
     193            void parentChanged();
     194            inline void scaleChanged()
     195                { this->setScale3D(this->getScale3D()); }
     196
    157197            WorldEntity* parent_;
    158198            unsigned int parentID_;
    159199            std::set<WorldEntity*> children_;
     200
     201
     202        /////////////
     203        // Physics //
     204        /////////////
     205
     206        public:
     207            /**
     208            @brief
     209                Denotes the possible types of physical objects in a Scene.
     210
     211                Dynamic:   The object is influenced by its physical environment, like for instance little ball.
     212                Kinematic: The object can only influence other dynamic objects. It's movement is coordinated by your own saying.
     213                Static:    Like kinematic but the object is not allowed to move during the simulation.
     214                None:      The object has no physics at all.
     215            */
     216            enum CollisionType
     217            {
     218                Dynamic,
     219                Kinematic,
     220                Static,
     221                None
     222            };
     223
     224            //! Tells whether the object has any connection to the Bullet physics engine. If hasPhysics() is false, the object may still have a velocity.
     225            bool hasPhysics()       const { return getCollisionType() != None     ; }
     226            //! @see CollisionType
     227            bool isStatic()         const { return getCollisionType() == Static   ; }
     228            //! @see CollisionType
     229            bool isKinematic()      const { return getCollisionType() == Kinematic; }
     230            //! @see CollisionType
     231            bool isDynamic()        const { return getCollisionType() == Dynamic  ; }
     232            //! Tells whether physics has been activated (you can temporarily deactivate it)
     233            bool isPhysicsActive()  const { return this->bPhysicsActive_; }
     234            bool addedToPhysicalWorld() const;
     235
     236            void activatePhysics();
     237            void deactivatePhysics();
     238
     239            //! Returns the CollisionType. @see CollisionType.
     240            inline CollisionType getCollisionType() const
     241                { return this->collisionType_; }
     242            void setCollisionType(CollisionType type);
     243
     244            void setCollisionTypeStr(const std::string& type);
     245            std::string getCollisionTypeStr() const;
     246
     247            //! Sets the mass of this object. Note that the total mass may be influenced by attached objects!
     248            inline void setMass(float mass)
     249                { this->mass_ = mass; recalculateMassProps(); }
     250            //! Returns the mass of this object without its children.
     251            inline float getMass() const
     252                { return this->mass_; }
     253
     254            //! Returns the total mass of this object with all its attached children.
     255            inline float getTotalMass() const
     256                { return this->mass_ + this->childrenMass_; }
     257
     258            /**
     259            @brief
     260                Returns the diagonal elements of the inertia tensor when calculated in local coordinates.
     261            @Note
     262                The local inertia tensor cannot be set, but is calculated by Bullet according to the collisionShape.
     263                With compound collision shapes, an approximation is used.
     264            */
     265            inline const btVector3& getLocalInertia() const
     266                { return this->localInertia_; }
     267
     268            /**
     269            @brief
     270                Sets how much reaction is applied in a collision.
     271               
     272                Consider two equal spheres colliding with equal velocities:
     273                Restitution 1 means that both spheres simply reverse their velocity (no loss of energy)
     274                Restitution 0 means that both spheres will immediately stop moving
     275                (maximum loss of energy without violating of the preservation of momentum)
     276            */
     277            inline void setRestitution(float restitution)
     278                { this->restitution_ = restitution; internalSetPhysicsProps(); }
     279            //! Returns the restitution parameter. @see setRestitution.
     280            inline float getRestitution() const
     281                { return this->restitution_; }
     282
     283            /**
     284            @brief
     285                Sets an artificial parameter that tells how much torque is applied when you apply a non-central force.
     286
     287                Normally the angular factor is 1, which means it's physically 'correct'. Howerver if you have a player
     288                character that should not rotate when hit sideways, you can set the angular factor to 0.
     289            */
     290            inline void setAngularFactor(float angularFactor)
     291                { this->angularFactor_ = angularFactor; internalSetPhysicsProps(); }
     292            //! Returns the angular factor. @see setAngularFactor.
     293            inline float getAngularFactor() const
     294                { return this->angularFactor_; }
     295
     296            //! Applies a mass independent damping. Velocities will simply diminish exponentially.
     297            inline void setLinearDamping(float linearDamping)
     298                { this->linearDamping_ = linearDamping; internalSetPhysicsProps(); }
     299            //! Returns the linear damping. @see setLinearDamping.
     300            inline float getLinearDamping() const
     301                { return this->linearDamping_; }
     302
     303            //! Applies a tensor independent rotation damping. Angular velocities will simply diminish exponentially.
     304            inline void setAngularDamping(float angularDamping)
     305                { this->angularDamping_ = angularDamping; internalSetPhysicsProps(); }
     306            //! Returns the angular damping. @see setAngularDamping.
     307            inline float getAngularDamping() const
     308                { return this->angularDamping_; }
     309
     310            //! Applies friction to the object. Friction occurs when two objects collide.
     311            inline void setFriction(float friction)
     312                { this->friction_ = friction; internalSetPhysicsProps(); }
     313            //! Returns the amount of friction applied to the object.
     314            inline float getFriction() const
     315                { return this->friction_; }
     316
     317            void attachCollisionShape(CollisionShape* shape);
     318            void detachCollisionShape(CollisionShape* shape);
     319            CollisionShape* getAttachedCollisionShape(unsigned int index);
     320
     321            void notifyCollisionShapeChanged();
     322            void notifyChildMassChanged();
     323
     324            /**
     325            @brief
     326                Virtual function that gets called when this object collides with another.
     327            @param otherObject
     328                The object this one has collided into.
     329            @pram contactPoint
     330                Contact point provided by Bullet. Holds more information and can me modified. See return value.
     331            @Return
     332                Returning false means that no modification to the contactPoint has been made. Return true otherwise!
     333            @Note
     334                Condition is that enableCollisionCallback() was called.
     335            */
     336            virtual inline bool collidesAgainst(WorldEntity* otherObject, btManifoldPoint& contactPoint)
     337                { return false; } /* With false, Bullet assumes no modification to the collision objects. */
     338
     339            //! Enables the collidesAgainst(.) function. The object doesn't respond to collision otherwise!
     340            inline void enableCollisionCallback()
     341                { this->bCollisionCallbackActive_ = true; this->collisionCallbackActivityChanged(); }
     342            //! Disables the collidesAgainst(.) function. @see enableCollisionCallback()
     343            inline void disableCollisionCallback()
     344                { this->bCollisionCallbackActive_ = false; this->collisionCallbackActivityChanged(); }
     345            //! Tells whether there could be a collision callback via collidesAgainst(.)
     346            inline bool isCollisionCallbackActive() const
     347                { return this->bCollisionCallbackActive_; }
     348
     349            //! Enables or disables collision response (default is of course on)
     350            inline void setCollisionResponse(bool value)
     351                { this->bCollisionResponseActive_ = value; this->collisionResponseActivityChanged(); }
     352            //! Tells whether there could be a collision response
     353            inline bool hasCollisionResponse()
     354                { return this->bCollisionResponseActive_; }
     355
     356        protected:
     357            /**
     358            @brief
     359                Function checks whether the requested collision type is legal to this object.
     360
     361                You can override this function in a derived class to constrain the collision to e.g. None or Dynamic.
     362                A projectile may not prove very useful if there is no physical body. Simply set the CollisionType
     363                in its constructor and override this method. But be careful that a derived classe's virtual functions
     364                don't yet exist in the constructor if a base class.
     365            */
     366            virtual bool isCollisionTypeLegal(CollisionType type) const = 0;
     367
     368            btRigidBody*  physicalBody_; //!< Bullet rigid body. Everything physical is applied to this instance.
     369
     370        private:
     371            void recalculateMassProps();
     372            void internalSetPhysicsProps();
     373
     374            bool notifyBeingAttached(WorldEntity* newParent);
     375            void notifyDetached();
     376
     377            // network callbacks
     378            void collisionTypeChanged();
     379            void physicsActivityChanged();
     380            void collisionCallbackActivityChanged();
     381            void collisionResponseActivityChanged();
     382            //! Network callback workaround to call a function when the value changes.
     383            inline void massChanged()
     384                { this->setMass(this->mass_); }
     385            //! Network callback workaround to call a function when the value changes.
     386            inline void restitutionChanged()
     387                { this->setRestitution(this->restitution_); }
     388            //! Network callback workaround to call a function when the value changes.
     389            inline void angularFactorChanged()
     390                { this->setAngularFactor(this->angularFactor_); }
     391            //! Network callback workaround to call a function when the value changes.
     392            inline void linearDampingChanged()
     393                { this->setLinearDamping(this->linearDamping_); }
     394            //! Network callback workaround to call a function when the value changes.
     395            inline void angularDampingChanged()
     396                { this->setAngularDamping(this->angularDamping_); }
     397            //! Network callback workaround to call a function when the value changes.
     398            inline void frictionChanged()
     399                { this->setFriction(this->friction_); }
     400
     401            CollisionType                collisionType_;                 //!< @see setCollisionType
     402            CollisionType                collisionTypeSynchronised_;     //!< Network synchronised variable for collisionType_
     403            bool                         bPhysicsActive_;                //!< @see isPhysicsActive
     404            bool                         bPhysicsActiveSynchronised_;    //!< Network synchronised variable for bPhysicsActive_
     405            //! When attaching objects hierarchically this variable tells this object (as child) whether physics was activated before attaching (because the deactivate physics while being attached).
     406            bool                         bPhysicsActiveBeforeAttaching_;
     407            WorldEntityCollisionShape*   collisionShape_;                //!< Attached collision shapes go here
     408            btScalar                     mass_;                          //!< @see setMass
     409            btVector3                    localInertia_;                  //!< @see getLocalInertia
     410            btScalar                     restitution_;                   //!< @see setRestitution
     411            btScalar                     angularFactor_;                 //!< @see setAngularFactor
     412            btScalar                     linearDamping_;                 //!< @see setLinearDamping
     413            btScalar                     angularDamping_;                //!< @see setAngularDamping
     414            btScalar                     friction_;                      //!< @see setFriction
     415            btScalar                     childrenMass_;                  //!< Sum of all the children's masses
     416            bool                         bCollisionCallbackActive_;      //!< @see enableCollisionCallback
     417            bool                         bCollisionResponseActive_;      //!< Tells whether the object should respond to collisions
    160418    };
     419
     420    // Inline heavily used functions for release builds. In debug, we better avoid including OgreSceneNode here.
     421#ifdef _NDEBUG
     422    inline const Vector3& WorldEntity::getPosition() const
     423        { return this->node_->getPosition(); }
     424    inline const Quaternion& WorldEntity::getOrientation() const
     425        { return this->node_->getrOrientation(); }
     426    inline const Vector3& WorldEntity::getScale3D(void) const
     427        { return this->node_->getScale(); }
     428#endif
     429
     430    SUPER_FUNCTION(5, WorldEntity, changedScale, false);
    161431}
    162432
  • code/trunk/src/orxonox/objects/worldentities/pawns/Pawn.cc

    r2171 r2662  
    3030#include "Pawn.h"
    3131
     32#include "core/Core.h"
    3233#include "core/CoreIncludes.h"
    3334#include "core/XMLPort.h"
    3435#include "util/Math.h"
     36#include "PawnManager.h"
    3537#include "objects/infos/PlayerInfo.h"
    3638#include "objects/gametypes/Gametype.h"
    37 #include "objects/weaponSystem/WeaponSystem.h"
     39#include "objects/worldentities/ParticleSpawner.h"
     40#include "objects/worldentities/ExplosionChunk.h"
    3841
    3942namespace orxonox
     
    4548        RegisterObject(Pawn);
    4649
    47         this->bAlive_ = false;
     50        PawnManager::touch();
     51        this->bAlive_ = true;
     52        this->fire_ = 0x0;
     53        this->firehack_ = 0x0;
    4854
    4955        this->health_ = 0;
     
    5258
    5359        this->lastHitOriginator_ = 0;
    54         this->weaponSystem_ = 0;
    55 
    56         /*
    57         //WeaponSystem
    58         weaponSystem_ = new WeaponSystem();
    59         WeaponSet * weaponSet1 = new WeaponSet(1);
    60         this->weaponSystem_->attachWeaponSet(weaponSet1);
    61         this->weaponSystem_->getWeaponSetPointer(0)->getWeaponSlotPointer(0)->setAmmoType(true);
    62         */
     60
     61        this->spawnparticleduration_ = 3.0f;
     62
     63        this->getPickUp().setPlayer(this);
     64
     65        if (Core::isMaster())
     66        {
     67            this->weaponSystem_ = new WeaponSystem(this);
     68            this->weaponSystem_->setParentPawn(this);
     69        }
     70        else
     71            this->weaponSystem_ = 0;
     72
     73        this->setRadarObjectColour(ColourValue::Red);
     74        this->setRadarObjectShape(RadarViewable::Dot);
    6375
    6476        this->registerVariables();
     
    6779    Pawn::~Pawn()
    6880    {
     81        if (this->isInitialized())
     82        {
     83            for (ObjectList<PawnListener>::iterator it = ObjectList<PawnListener>::begin(); it != ObjectList<PawnListener>::end(); ++it)
     84                it->destroyedPawn(this);
     85
     86            if (this->weaponSystem_)
     87                delete this->weaponSystem_;
     88        }
    6989    }
    7090
     
    7393        SUPER(Pawn, XMLPort, xmlelement, mode);
    7494
    75         XMLPortParam(Pawn, "health", setHealth, getHealht, xmlelement, mode).defaultValues(100);
     95        XMLPortParam(Pawn, "health", setHealth, getHealth, xmlelement, mode).defaultValues(100);
    7696        XMLPortParam(Pawn, "maxhealth", setMaxHealth, getMaxHealth, xmlelement, mode).defaultValues(200);
    7797        XMLPortParam(Pawn, "initialhealth", setInitialHealth, getInitialHealth, xmlelement, mode).defaultValues(100);
     98        XMLPortParam(Pawn, "spawnparticlesource", setSpawnParticleSource, getSpawnParticleSource, xmlelement, mode);
     99        XMLPortParam(Pawn, "spawnparticleduration", setSpawnParticleDuration, getSpawnParticleDuration, xmlelement, mode).defaultValues(3.0f);
     100        XMLPortParam(Pawn, "explosionchunks", setExplosionChunks, getExplosionChunks, xmlelement, mode).defaultValues(7);
     101
     102        XMLPortObject(Pawn, WeaponSlot, "weaponslots", setWeaponSlot, getWeaponSlot, xmlelement, mode);
     103        XMLPortObject(Pawn, WeaponSet, "weaponsets", setWeaponSet, getWeaponSet, xmlelement, mode);
     104        XMLPortObject(Pawn, WeaponPack, "weapons", setWeaponPack, getWeaponPack, xmlelement, mode);
    78105    }
    79106
    80107    void Pawn::registerVariables()
    81108    {
    82         REGISTERDATA(this->bAlive_, direction::toclient);
    83         REGISTERDATA(this->health_, direction::toclient);
     109        registerVariable(this->bAlive_,        variableDirection::toclient);
     110        registerVariable(this->health_,        variableDirection::toclient);
     111        registerVariable(this->initialHealth_, variableDirection::toclient);
     112        registerVariable(this->fire_,          variableDirection::toserver);
    84113    }
    85114
     
    87116    {
    88117        SUPER(Pawn, tick, dt);
     118
     119        if (this->weaponSystem_)
     120        {
     121            if (this->fire_ & WeaponMode::fire)
     122                this->weaponSystem_->fire(WeaponMode::fire);
     123            if (this->fire_ & WeaponMode::altFire)
     124                this->weaponSystem_->fire(WeaponMode::altFire);
     125            if (this->fire_ & WeaponMode::altFire2)
     126                this->weaponSystem_->fire(WeaponMode::altFire2);
     127        }
     128        this->fire_ = this->firehack_;
     129        this->firehack_ = 0x0;
    89130
    90131        if (this->health_ <= 0)
     
    119160    }
    120161
    121     void Pawn::spawn()
     162    void Pawn::spawneffect()
    122163    {
    123164        // play spawn effect
     165        if (this->spawnparticlesource_ != "")
     166        {
     167            ParticleSpawner* effect = new ParticleSpawner(this->getCreator());
     168            effect->setPosition(this->getPosition());
     169            effect->setOrientation(this->getOrientation());
     170            effect->setDestroyAfterLife(true);
     171            effect->setSource(this->spawnparticlesource_);
     172            effect->setLifetime(this->spawnparticleduration_);
     173        }
    124174    }
    125175
    126176    void Pawn::death()
    127177    {
     178        // Set bAlive_ to false and wait for PawnManager to do the destruction
    128179        this->bAlive_ = false;
     180
     181        this->setDestroyWhenPlayerLeft(false);
     182
    129183        if (this->getGametype())
    130184            this->getGametype()->pawnKilled(this, this->lastHitOriginator_);
     185
    131186        if (this->getPlayer())
    132187            this->getPlayer()->stopControl(this);
    133188
    134         delete this;
    135 
     189        if (Core::isMaster())
     190            this->deatheffect();
     191    }
     192
     193    void Pawn::deatheffect()
     194    {
    136195        // play death effect
    137     }
    138 
    139     void Pawn::fire()
    140     {
    141         if (this->weaponSystem_)
    142             this->weaponSystem_->fire();
     196        {
     197            ParticleSpawner* effect = new ParticleSpawner(this->getCreator());
     198            effect->setPosition(this->getPosition());
     199            effect->setOrientation(this->getOrientation());
     200            effect->setDestroyAfterLife(true);
     201            effect->setSource("Orxonox/explosion2b");
     202            effect->setLifetime(4.0f);
     203        }
     204        {
     205            ParticleSpawner* effect = new ParticleSpawner(this->getCreator());
     206            effect->setPosition(this->getPosition());
     207            effect->setOrientation(this->getOrientation());
     208            effect->setDestroyAfterLife(true);
     209            effect->setSource("Orxonox/smoke6");
     210            effect->setLifetime(4.0f);
     211        }
     212        {
     213            ParticleSpawner* effect = new ParticleSpawner(this->getCreator());
     214            effect->setPosition(this->getPosition());
     215            effect->setOrientation(this->getOrientation());
     216            effect->setDestroyAfterLife(true);
     217            effect->setSource("Orxonox/sparks");
     218            effect->setLifetime(4.0f);
     219        }
     220        for (unsigned int i = 0; i < this->numexplosionchunks_; ++i)
     221        {
     222            ExplosionChunk* chunk = new ExplosionChunk(this->getCreator());
     223            chunk->setPosition(this->getPosition());
     224
     225        }
     226    }
     227
     228    void Pawn::fire(WeaponMode::Enum fireMode)
     229    {
     230        this->firehack_ |= fireMode;
    143231    }
    144232
     
    146234    {
    147235        this->setHealth(this->initialHealth_);
    148         this->spawn();
     236        if (Core::isMaster())
     237            this->spawneffect();
     238    }
     239
     240    void Pawn::dropItems()
     241    {
     242        pickUp.eraseAll();
     243    }
     244
     245    void Pawn::setWeaponSlot(WeaponSlot * wSlot)
     246    {
     247        this->attach(wSlot);
     248        if (this->weaponSystem_)
     249            this->weaponSystem_->attachWeaponSlot(wSlot);
     250    }
     251
     252    WeaponSlot * Pawn::getWeaponSlot(unsigned int index) const
     253    {
     254        if (this->weaponSystem_)
     255            return this->weaponSystem_->getWeaponSlotPointer(index);
     256        else
     257            return 0;
     258    }
     259
     260    void Pawn::setWeaponPack(WeaponPack * wPack)
     261    {
     262        if (this->weaponSystem_)
     263        {
     264            wPack->setParentWeaponSystem(this->weaponSystem_);
     265            wPack->setParentWeaponSystemToAllWeapons(this->weaponSystem_);
     266            this->weaponSystem_->attachWeaponPack( wPack,wPack->getFireMode() );
     267            wPack->attachNeededMunitionToAllWeapons();
     268        }
     269    }
     270
     271    WeaponPack * Pawn::getWeaponPack(unsigned int firemode) const
     272    {
     273        if (this->weaponSystem_)
     274            return this->weaponSystem_->getWeaponPackPointer(firemode);
     275        else
     276            return 0;
     277    }
     278
     279    void Pawn::setWeaponSet(WeaponSet * wSet)
     280    {
     281        if (this->weaponSystem_)
     282            this->weaponSystem_->attachWeaponSet(wSet);
     283    }
     284
     285    WeaponSet * Pawn::getWeaponSet(unsigned int index) const
     286    {
     287        if (this->weaponSystem_)
     288            return this->weaponSystem_->getWeaponSetPointer(index);
     289        else
     290            return 0;
     291    }
     292
     293
     294    ///////////////////
     295    // Pawn Listener //
     296    ///////////////////
     297    PawnListener::PawnListener()
     298    {
     299        RegisterRootObject(PawnListener);
    149300    }
    150301}
  • code/trunk/src/orxonox/objects/worldentities/pawns/Pawn.h

    r2098 r2662  
    3131
    3232#include "OrxonoxPrereqs.h"
    33 
     33#include "objects/pickup/ShipEquipment.h"
    3434#include "objects/worldentities/ControllableEntity.h"
     35#include "objects/RadarViewable.h"
     36#include "objects/weaponSystem/WeaponSystem.h"
    3537
    3638namespace orxonox
    3739{
    38     class _OrxonoxExport Pawn : public ControllableEntity
     40    class _OrxonoxExport Pawn : public ControllableEntity, public RadarViewable
    3941    {
    4042        public:
     
    5456            inline void removeHealth(float health)
    5557                { this->setHealth(this->health_ - health); }
    56             inline float getHealht() const
     58            inline float getHealth() const
    5759                { return this->health_; }
    5860
     
    7476            virtual void kill();
    7577
    76             virtual void fire();
    77 
     78            virtual void fire(WeaponMode::Enum fireMode);
    7879            virtual void postSpawn();
    7980
     81            void setWeaponSlot(WeaponSlot * wSlot);
     82            WeaponSlot * getWeaponSlot(unsigned int index) const;
     83            void setWeaponPack(WeaponPack * wPack);
     84            WeaponPack * getWeaponPack(unsigned int firemode) const;
     85            void setWeaponSet(WeaponSet * wSet);
     86            WeaponSet * getWeaponSet(unsigned int index) const;
     87
     88            inline const WorldEntity* getWorldEntity() const
     89                { return const_cast<Pawn*>(this); }
     90
     91            inline void setSpawnParticleSource(const std::string& source)
     92                { this->spawnparticlesource_ = source; }
     93            inline const std::string& getSpawnParticleSource() const
     94                { return this->spawnparticlesource_; }
     95
     96            inline void setSpawnParticleDuration(float duration)
     97                { this->spawnparticleduration_ = duration; }
     98            inline float getSpawnParticleDuration() const
     99                { return this->spawnparticleduration_; }
     100
     101            inline void setExplosionChunks(unsigned int chunks)
     102                { this->numexplosionchunks_ = chunks; }
     103            inline unsigned int getExplosionChunks() const
     104                { return this->numexplosionchunks_; }
     105
     106            inline ShipEquipment& getPickUp()
     107                {return this->pickUp;}
     108
     109            virtual void dropItems();
     110
    80111        protected:
    81             virtual void spawn();
    82112            virtual void death();
     113            virtual void deatheffect();
     114            virtual void spawneffect();
    83115
     116            ShipEquipment pickUp;
    84117            bool bAlive_;
     118
    85119
    86120            float health_;
     
    91125
    92126            WeaponSystem* weaponSystem_;
     127            unsigned int fire_;
     128            unsigned int firehack_;
     129
     130            std::string spawnparticlesource_;
     131            float spawnparticleduration_;
     132            unsigned int numexplosionchunks_;
     133    };
     134
     135    class _OrxonoxExport PawnListener : virtual public OrxonoxClass
     136    {
     137        friend class Pawn;
     138
     139        public:
     140            PawnListener();
     141            virtual ~PawnListener() {}
     142
     143        protected:
     144            virtual void destroyedPawn(Pawn* pawn) = 0;
    93145    };
    94146}
  • code/trunk/src/orxonox/objects/worldentities/pawns/SpaceShip.cc

    r2171 r2662  
    3030#include "SpaceShip.h"
    3131
     32#include "BulletDynamics/Dynamics/btRigidBody.h"
     33
     34#include "util/Math.h"
     35#include "util/Exception.h"
    3236#include "core/CoreIncludes.h"
    3337#include "core/ConfigValueIncludes.h"
     38#include "core/Template.h"
    3439#include "core/XMLPort.h"
    35 #include "util/Math.h"
     40#include "objects/items/Engine.h"
    3641
    3742namespace orxonox
    3843{
     44    const float orientationGain = 100;
    3945    CreateFactory(SpaceShip);
    4046
     
    4349        RegisterObject(SpaceShip);
    4450
    45         this->zeroDegree_ = 0;
    46 
    47         this->maxSpeed_ = 0;
    48         this->maxSecondarySpeed_ = 0;
    49         this->maxRotation_ = 0;
    50         this->translationAcceleration_ = 0;
    51         this->rotationAcceleration_ = 0;
    52         this->translationDamping_ = 0;
    53 
    54         this->yawRotation_ = 0;
    55         this->pitchRotation_ = 0;
    56         this->rollRotation_ = 0;
     51        this->primaryThrust_  = 100;
     52        this->auxilaryThrust_ =  30;
     53        this->rotationThrust_ =  10;
     54
     55        this->localLinearAcceleration_.setValue(0, 0, 0);
     56        this->localAngularAcceleration_.setValue(0, 0, 0);
     57        this->bBoost_ = false;
     58        this->bPermanentBoost_ = false;
     59        this->steering_ = Vector3::ZERO;
     60        this->engine_ = 0;
     61
    5762
    5863        this->bInvertYAxis_ = false;
    5964
    6065        this->setDestroyWhenPlayerLeft(true);
     66
     67        // SpaceShip is always a physical object per default
     68        // Be aware of this call: The collision type legality check will not reach derived classes!
     69        this->setCollisionType(WorldEntity::Dynamic);
     70        // Get notification about collisions
     71        this->enableCollisionCallback();
    6172
    6273        this->setConfigValues();
     
    6677    SpaceShip::~SpaceShip()
    6778    {
     79        if (this->isInitialized() && this->engine_)
     80            delete this->engine_;
    6881    }
    6982
     
    7285        SUPER(SpaceShip, XMLPort, xmlelement, mode);
    7386
    74         XMLPortParam(SpaceShip, "maxspeed",          setMaxSpeed,          getMaxSpeed,          xmlelement, mode);
    75         XMLPortParam(SpaceShip, "maxsecondaryspeed", setMaxSecondarySpeed, getMaxSecondarySpeed, xmlelement, mode);
    76         XMLPortParam(SpaceShip, "maxrotation",       setMaxRotation,       getMaxRotation,       xmlelement, mode);
    77         XMLPortParam(SpaceShip, "transacc",          setTransAcc,          getTransAcc,          xmlelement, mode);
    78         XMLPortParam(SpaceShip, "rotacc",            setRotAcc,            getRotAcc,            xmlelement, mode);
    79         XMLPortParam(SpaceShip, "transdamp",         setTransDamp,         getTransDamp,         xmlelement, mode);
     87        XMLPortParam(SpaceShip, "engine",            setEngineTemplate,    getEngineTemplate,    xmlelement, mode);
     88        XMLPortParamVariable(SpaceShip, "primaryThrust",  primaryThrust_,  xmlelement, mode);
     89        XMLPortParamVariable(SpaceShip, "auxilaryThrust", auxilaryThrust_, xmlelement, mode);
     90        XMLPortParamVariable(SpaceShip, "rotationThrust", rotationThrust_, xmlelement, mode);
    8091    }
    8192
    8293    void SpaceShip::registerVariables()
    8394    {
    84         REGISTERDATA(this->maxSpeed_,                direction::toclient);
    85         REGISTERDATA(this->maxSecondarySpeed_,       direction::toclient);
    86         REGISTERDATA(this->maxRotation_,             direction::toclient);
    87         REGISTERDATA(this->translationAcceleration_, direction::toclient);
    88         REGISTERDATA(this->rotationAcceleration_,    direction::toclient);
    89         REGISTERDATA(this->translationDamping_,      direction::toclient);
     95        registerVariable(this->primaryThrust_,  variableDirection::toclient);
     96        registerVariable(this->auxilaryThrust_, variableDirection::toclient);
     97        registerVariable(this->rotationThrust_, variableDirection::toclient);
    9098    }
    9199
     
    95103    }
    96104
     105    bool SpaceShip::isCollisionTypeLegal(WorldEntity::CollisionType type) const
     106    {
     107        if (type != WorldEntity::Dynamic)
     108        {
     109            CCOUT(1) << "Error: Cannot tell a SpaceShip not to be dynamic! Ignoring." << std::endl;
     110            assert(false); // Only in debug mode
     111            return false;
     112        }
     113        else
     114            return true;
     115    }
     116
    97117    void SpaceShip::tick(float dt)
    98118    {
    99         if (this->isLocallyControlled())
     119        SUPER(SpaceShip, tick, dt);
     120
     121        if (this->hasLocalController())
    100122        {
    101             // #####################################
    102             // ############# STEERING ##############
    103             // #####################################
    104 
    105             Vector3 velocity = this->getVelocity();
    106             if (velocity.x > this->maxSecondarySpeed_)
    107                 velocity.x = this->maxSecondarySpeed_;
    108             if (velocity.x < -this->maxSecondarySpeed_)
    109                 velocity.x = -this->maxSecondarySpeed_;
    110             if (velocity.y > this->maxSecondarySpeed_)
    111                 velocity.y = this->maxSecondarySpeed_;
    112             if (velocity.y < -this->maxSecondarySpeed_)
    113                 velocity.y = -this->maxSecondarySpeed_;
    114             if (velocity.z > this->maxSecondarySpeed_)
    115                 velocity.z = this->maxSecondarySpeed_;
    116             if (velocity.z < -this->maxSpeed_)
    117                 velocity.z = -this->maxSpeed_;
    118 
    119             // normalize velocity and acceleration
    120             for (size_t dimension = 0; dimension < 3; ++dimension)
     123/*
     124            this->localLinearAcceleration_.setX(this->localLinearAcceleration_.x() * getMass() * this->auxilaryThrust_);
     125            this->localLinearAcceleration_.setY(this->localLinearAcceleration_.y() * getMass() * this->auxilaryThrust_);
     126            if (this->localLinearAcceleration_.z() > 0)
     127                this->localLinearAcceleration_.setZ(this->localLinearAcceleration_.z() * getMass() * this->auxilaryThrust_);
     128            else
     129                this->localLinearAcceleration_.setZ(this->localLinearAcceleration_.z() * getMass() * this->primaryThrust_);
     130            this->physicalBody_->applyCentralForce(physicalBody_->getWorldTransform().getBasis() * this->localLinearAcceleration_);
     131            this->localLinearAcceleration_.setValue(0, 0, 0);
     132*/
     133            if (!this->isInMouseLook())
    121134            {
    122                 if (this->acceleration_[dimension] == 0)
     135                this->localAngularAcceleration_ *= this->getLocalInertia() * this->rotationThrust_;
     136                this->physicalBody_->applyTorque(physicalBody_->getWorldTransform().getBasis() * this->localAngularAcceleration_);
     137                this->localAngularAcceleration_.setValue(0, 0, 0);
     138            }
     139        }
     140    }
     141
     142    void SpaceShip::moveFrontBack(const Vector2& value)
     143    {
     144        this->localLinearAcceleration_.setZ(this->localLinearAcceleration_.z() - value.x);
     145        this->steering_.z = -value.x;
     146    }
     147
     148    void SpaceShip::moveRightLeft(const Vector2& value)
     149    {
     150        this->localLinearAcceleration_.setX(this->localLinearAcceleration_.x() + value.x);
     151        this->steering_.x = value.x;
     152    }
     153
     154    void SpaceShip::moveUpDown(const Vector2& value)
     155    {
     156        this->localLinearAcceleration_.setY(this->localLinearAcceleration_.y() + value.x);
     157        this->steering_.y = value.x;
     158    }
     159
     160    void SpaceShip::rotateYaw(const Vector2& value)
     161    {
     162        this->localAngularAcceleration_.setY(this->localAngularAcceleration_.y() - value.x);
     163
     164        Pawn::rotateYaw(value);
     165    }
     166
     167    void SpaceShip::rotatePitch(const Vector2& value)
     168    {
     169        this->localAngularAcceleration_.setX(this->localAngularAcceleration_.x() + value.x);
     170
     171        Pawn::rotatePitch(value);
     172    }
     173
     174    void SpaceShip::rotateRoll(const Vector2& value)
     175    {
     176        this->localAngularAcceleration_.setZ(this->localAngularAcceleration_.z() + value.x);
     177
     178        Pawn::rotateRoll(value);
     179    }
     180
     181    void SpaceShip::fire()
     182    {
     183    }
     184
     185    void SpaceShip::boost()
     186    {
     187        this->bBoost_ = true;
     188    }
     189
     190    void SpaceShip::loadEngineTemplate()
     191    {
     192        if (this->enginetemplate_ != "")
     193        {
     194            Template* temp = Template::getTemplate(this->enginetemplate_);
     195
     196            if (temp)
     197            {
     198                Identifier* identifier = temp->getBaseclassIdentifier();
     199
     200                if (identifier)
    123201                {
    124                     if (velocity[dimension] > 0)
     202                    BaseObject* object = identifier->fabricate(this);
     203                    this->engine_ = dynamic_cast<Engine*>(object);
     204
     205                    if (this->engine_)
    125206                    {
    126                         velocity[dimension] -= (this->translationDamping_ * dt);
    127                         if (velocity[dimension] < 0)
    128                             velocity[dimension] = 0;
     207                        this->engine_->addTemplate(temp);
     208                        this->engine_->addToSpaceShip(this);
    129209                    }
    130                     else if (velocity[dimension] < 0)
     210                    else
    131211                    {
    132                         velocity[dimension] += (this->translationDamping_ * dt);
    133                         if (velocity[dimension] > 0)
    134                             velocity[dimension] = 0;
     212                        delete object;
    135213                    }
    136214                }
    137215            }
    138 
    139             this->setVelocity(velocity);
    140216        }
    141 
    142 
    143         SUPER(SpaceShip, tick, dt);
    144 
    145 
    146         if (this->isLocallyControlled())
    147         {
    148             this->yaw(this->yawRotation_ * dt);
    149             if (this->bInvertYAxis_)
    150                 this->pitch(Degree(-this->pitchRotation_ * dt));
    151             else
    152                 this->pitch(Degree( this->pitchRotation_ * dt));
    153             this->roll(this->rollRotation_ * dt);
    154 
    155             this->acceleration_.x = 0;
    156             this->acceleration_.y = 0;
    157             this->acceleration_.z = 0;
    158 
    159             this->yawRotation_   = this->zeroDegree_;
    160             this->pitchRotation_ = this->zeroDegree_;
    161             this->rollRotation_  = this->zeroDegree_;
    162         }
    163     }
    164 
    165     void SpaceShip::moveFrontBack(const Vector2& value)
    166     {
    167         this->acceleration_.z = -this->translationAcceleration_ * value.x;
    168     }
    169 
    170     void SpaceShip::moveRightLeft(const Vector2& value)
    171     {
    172         this->acceleration_.x = this->translationAcceleration_ * value.x;
    173     }
    174 
    175     void SpaceShip::moveUpDown(const Vector2& value)
    176     {
    177         this->acceleration_.y = this->translationAcceleration_ * value.x;
    178     }
    179 
    180     void SpaceShip::rotateYaw(const Vector2& value)
    181     {
    182         Degree temp = value.x * value.x * sgn(value.x) * this->rotationAcceleration_;
    183         if (temp > this->maxRotation_)
    184             temp = this->maxRotation_;
    185         if (temp < -this->maxRotation_)
    186             temp = -this->maxRotation_;
    187         this->yawRotation_ = Degree(temp);
    188     }
    189 
    190     void SpaceShip::rotatePitch(const Vector2& value)
    191     {
    192         Degree temp = value.x * value.x * sgn(value.x) * this->rotationAcceleration_;
    193         if (temp > this->maxRotation_)
    194             temp = this->maxRotation_;
    195         if (temp < -this->maxRotation_)
    196             temp = -this->maxRotation_;
    197         this->pitchRotation_ = Degree(temp);
    198     }
    199 
    200     void SpaceShip::rotateRoll(const Vector2& value)
    201     {
    202         Degree temp = value.x * value.x * sgn(value.x) * this->rotationAcceleration_;
    203         if (temp > this->maxRotation_)
    204             temp = this->maxRotation_;
    205         if (temp < -this->maxRotation_)
    206             temp = -this->maxRotation_;
    207         this->rollRotation_ = Degree(temp);
    208     }
    209 
    210     void SpaceShip::fire()
    211     {
     217    }
     218
     219    void SpaceShip::setEngine(Engine* engine)
     220    {
     221        this->engine_ = engine;
     222        if (engine && engine->getShip() != this)
     223            engine->addToSpaceShip(this);
    212224    }
    213225}
  • code/trunk/src/orxonox/objects/worldentities/pawns/SpaceShip.h

    r2087 r2662  
    3232#include "OrxonoxPrereqs.h"
    3333
     34#include "LinearMath/btVector3.h"
     35
    3436#include "Pawn.h"
    3537
     
    5658
    5759            virtual void fire();
     60            virtual void boost();
    5861
    59             void setMaxSpeed(float value)
    60                 { this->maxSpeed_ = value; }
    61             void setMaxSecondarySpeed(float value)
    62                 { this->maxSecondarySpeed_ = value; }
    63             void setMaxRotation(const Degree& value)
    64                 { this->maxRotation_ = value; }
    65             void setTransAcc(float value)
    66                 { this->translationAcceleration_ = value; }
    67             void setRotAcc(const Degree& value)
    68                 { this->rotationAcceleration_ = value; }
    69             void setTransDamp(float value)
    70                 { this->translationDamping_ = value; }
     62            void setEngine(Engine* engine);
     63            inline Engine* getEngine() const
     64                { return this->engine_; }
    7165
    72             inline float getMaxSpeed() const
    73                 { return this->maxSpeed_; }
    74             inline float getMaxSecondarySpeed() const
    75                 { return this->maxSecondarySpeed_; }
    76             inline float getMaxRotation() const
    77                 { return this->maxRotation_.valueDegrees(); }
    78             inline float getTransAcc() const
    79                 { return this->translationAcceleration_; }
    80             inline float getRotAcc() const
    81                 { return this->rotationAcceleration_.valueDegrees(); }
    82             inline float getTransDamp() const
    83                 { return this->translationDamping_; }
     66            inline void setSteeringDirection(const Vector3& direction)
     67                { this->steering_ = direction; }
     68            inline const Vector3& getSteeringDirection() const
     69                { return this->steering_; }
     70
     71            inline void setBoost(bool bBoost)
     72                { this->bBoost_ = bBoost; }
     73            inline bool getBoost() const
     74                { return this->bBoost_; }
     75
     76            inline void setEngineTemplate(const std::string& temp)
     77                { this->enginetemplate_ = temp; this->loadEngineTemplate(); }
     78            inline const std::string& getEngineTemplate() const
     79                { return this->enginetemplate_; }
     80
     81            inline void setPermanentBoost(bool bPermanent)
     82                { this->bPermanentBoost_ = bPermanent; }
     83            inline bool getPermanentBoost() const
     84                { return this->bPermanentBoost_; }
    8485
    8586        protected:
    8687            bool bInvertYAxis_;
    8788
    88             float maxSpeed_;
    89             float maxSecondarySpeed_;
    90             float translationAcceleration_;
    91             float translationDamping_;
     89            bool bBoost_;
     90            bool bPermanentBoost_;
     91            Vector3 steering_;
     92            float primaryThrust_;
     93            float auxilaryThrust_;
     94            float rotationThrust_;
     95            btVector3 localLinearAcceleration_;
     96            btVector3 localAngularAcceleration_;
    9297
    93             Degree maxRotation_;
    94             Degree rotationAcceleration_;
     98        private:
     99            virtual bool isCollisionTypeLegal(WorldEntity::CollisionType type) const;
    95100
    96             Degree zeroDegree_;
    97             Degree pitchRotation_;
    98             Degree yawRotation_;
    99             Degree rollRotation_;
     101        private:
     102            void loadEngineTemplate();
     103
     104            std::string enginetemplate_;
     105            Engine* engine_;
    100106    };
    101107}
  • code/trunk/src/orxonox/objects/worldentities/pawns/Spectator.cc

    r2171 r2662  
    3030#include "Spectator.h"
    3131
     32#include <OgreBillboardSet.h>
     33
    3234#include "core/CoreIncludes.h"
     35#include "core/ConfigValueIncludes.h"
    3336#include "core/Core.h"
    3437#include "objects/worldentities/Model.h"
     
    4952        RegisterObject(Spectator);
    5053
    51         this->speed_ = 100;
    52         this->rotationSpeed_ = 3;
     54        this->speed_ = 200;
    5355
    5456        this->yaw_ = 0;
    5557        this->pitch_ = 0;
    5658        this->roll_ = 0;
     59        this->localVelocity_ = Vector3::ZERO;
    5760        this->setHudTemplate("spectatorhud");
    58         this->hudmode_ = 0;
     61        this->greetingFlare_ = 0;
    5962
    6063        this->setDestroyWhenPlayerLeft(true);
    6164
    62         this->greetingFlare_ = new BillboardSet();
    63         this->greetingFlare_->setBillboardSet(this->getScene()->getSceneManager(), "Examples/Flare", ColourValue(1.0, 1.0, 0.8), Vector3(0, 20, 0), 1);
    64         if (this->greetingFlare_->getBillboardSet())
    65             this->getNode()->attachObject(this->greetingFlare_->getBillboardSet());
    66         this->greetingFlare_->setVisible(false);
     65        if (Core::showsGraphics())
     66        {
     67            this->greetingFlare_ = new BillboardSet();
     68            this->greetingFlare_->setBillboardSet(this->getScene()->getSceneManager(), "Examples/Flare", ColourValue(1.0, 1.0, 0.8), Vector3(0, 20, 0), 1);
     69            if (this->greetingFlare_->getBillboardSet())
     70                this->attachOgreObject(this->greetingFlare_->getBillboardSet());
     71            this->greetingFlare_->setVisible(false);
     72        }
     73
    6774        this->bGreetingFlareVisible_ = false;
    6875        this->bGreeting_ = false;
    6976
     77        this->setConfigValues();
    7078        this->registerVariables();
    7179    }
     
    7886            {
    7987                if (this->greetingFlare_->getBillboardSet())
    80                     this->getNode()->detachObject(this->greetingFlare_->getBillboardSet());
     88                    this->detachOgreObject(this->greetingFlare_->getBillboardSet());
     89
    8190                delete this->greetingFlare_;
    8291            }
     
    8493    }
    8594
     95    void Spectator::setConfigValues()
     96    {
     97        SetConfigValue(speed_, 200.0f);
     98    }
     99
    86100    void Spectator::registerVariables()
    87101    {
    88         REGISTERDATA(this->bGreetingFlareVisible_, direction::toclient, new NetworkCallback<Spectator>(this, &Spectator::changedFlareVisibility));
    89         REGISTERDATA(this->bGreeting_,             direction::toserver, new NetworkCallback<Spectator>(this, &Spectator::changedGreeting));
    90         REGISTERDATA(this->hudmode_,               direction::toclient);
     102        registerVariable(this->bGreetingFlareVisible_, variableDirection::toclient, new NetworkCallback<Spectator>(this, &Spectator::changedFlareVisibility));
     103        registerVariable(this->bGreeting_,             variableDirection::toserver, new NetworkCallback<Spectator>(this, &Spectator::changedGreeting));
    91104    }
    92105
     
    99112    void Spectator::changedFlareVisibility()
    100113    {
    101         this->greetingFlare_->setVisible(this->bGreetingFlareVisible_);
     114        if ( this->greetingFlare_ )
     115            this->greetingFlare_->setVisible(this->bGreetingFlareVisible_);
    102116    }
    103117
    104118    void Spectator::tick(float dt)
    105119    {
    106         this->updateHUD();
    107 
    108         if (this->isLocallyControlled())
    109         {
    110             Vector3 velocity = this->getVelocity();
    111             velocity.normalise();
    112             this->setVelocity(velocity * this->speed_);
    113 
    114             this->yaw(Radian(this->yaw_ * this->rotationSpeed_));
    115             this->pitch(Radian(this->pitch_ * this->rotationSpeed_));
    116             this->roll(Radian(this->roll_ * this->rotationSpeed_));
     120        if (this->hasLocalController())
     121        {
     122            float localSpeedSquared = this->localVelocity_.squaredLength();
     123            float localSpeed;
     124            if (localSpeedSquared > 1.0)
     125                localSpeed = this->speed_ / sqrtf(localSpeedSquared);
     126            else
     127                localSpeed = this->speed_;
     128
     129            this->localVelocity_.x *= localSpeed;
     130            this->localVelocity_.y *= localSpeed;
     131            this->localVelocity_.z *= localSpeed;
     132            this->setVelocity(this->getOrientation() * this->localVelocity_);
     133            this->localVelocity_.x = 0;
     134            this->localVelocity_.y = 0;
     135            this->localVelocity_.z = 0;
     136
     137            if (!this->isInMouseLook())
     138            {
     139                this->yaw(Radian(this->yaw_ * this->getMouseLookSpeed()));
     140                this->pitch(Radian(this->pitch_ * this->getMouseLookSpeed()));
     141                this->roll(Radian(this->roll_ * this->getMouseLookSpeed()));
     142            }
    117143
    118144            this->yaw_ = this->pitch_ = this->roll_ = 0;
     
    120146
    121147        SUPER(Spectator, tick, dt);
    122 
    123         if (this->isLocallyControlled())
    124         {
    125             this->setVelocity(Vector3::ZERO);
    126         }
    127148    }
    128149
     
    131152        ControllableEntity::setPlayer(player);
    132153
    133 //        this->setObjectMode(direction::toclient);
    134     }
    135 
    136     void Spectator::startLocalControl()
    137     {
    138         ControllableEntity::startLocalControl();
    139 //        if (this->isLocallyControlled())
    140 //            this->testmesh_->setVisible(false);
     154//        this->setObjectMode(objectDirection::toclient);
     155    }
     156
     157    void Spectator::startLocalHumanControl()
     158    {
     159        ControllableEntity::startLocalHumanControl();
    141160    }
    142161
    143162    void Spectator::moveFrontBack(const Vector2& value)
    144163    {
    145         this->setVelocity(this->getVelocity() + value.y * this->speed_ * WorldEntity::FRONT);
     164        this->localVelocity_.z -= value.x;
    146165    }
    147166
    148167    void Spectator::moveRightLeft(const Vector2& value)
    149168    {
    150         this->setVelocity(this->getVelocity() + value.y * this->speed_ * WorldEntity::RIGHT);
     169        this->localVelocity_.x += value.x;
    151170    }
    152171
    153172    void Spectator::moveUpDown(const Vector2& value)
    154173    {
    155         this->setVelocity(this->getVelocity() + value.y * this->speed_ * WorldEntity::UP);
     174        this->localVelocity_.y += value.x;
    156175    }
    157176
    158177    void Spectator::rotateYaw(const Vector2& value)
    159178    {
    160         this->yaw_ = value.y;
     179        this->yaw_ -= value.y;
     180
     181        ControllableEntity::rotateYaw(value);
    161182    }
    162183
    163184    void Spectator::rotatePitch(const Vector2& value)
    164185    {
    165         this->pitch_ = value.y;
     186        this->pitch_ += value.y;
     187
     188        ControllableEntity::rotatePitch(value);
    166189    }
    167190
    168191    void Spectator::rotateRoll(const Vector2& value)
    169192    {
    170         this->roll_ = value.y;
    171     }
    172 
    173     void Spectator::fire()
     193        this->roll_ += value.y;
     194
     195        ControllableEntity::rotateRoll(value);
     196    }
     197
     198    void Spectator::fire(WeaponMode::Enum fireMode)
    174199    {
    175200        if (this->getPlayer())
     
    187212        }
    188213    }
    189 
    190     void Spectator::updateHUD()
    191     {
    192         // <hack>
    193         if (Core::isMaster())
    194         {
    195             if (this->getPlayer() && this->getGametype())
    196             {
    197                 if (!this->getGametype()->hasStarted() && !this->getGametype()->isStartCountdownRunning())
    198                 {
    199                     if (!this->getPlayer()->isReadyToSpawn())
    200                         this->hudmode_ = 0;
    201                     else
    202                         this->hudmode_ = 1;
    203                 }
    204                 else if (!this->getGametype()->hasEnded())
    205                 {
    206                     if (this->getGametype()->isStartCountdownRunning())
    207                         this->hudmode_ = 2 + 10*(int)ceil(this->getGametype()->getStartCountdown());
    208                     else
    209                         this->hudmode_ = 3;
    210                 }
    211                 else
    212                     this->hudmode_ = 4;
    213             }
    214             else
    215                 return;
    216         }
    217 
    218         if (this->getHUD())
    219         {
    220             std::string text;
    221             int hudmode = this->hudmode_ % 10;
    222 
    223             switch (hudmode)
    224             {
    225                 case 0:
    226                     text = "Press [Fire] to start the match";
    227                     break;
    228                 case 1:
    229                     text = "Waiting for other players";
    230                     break;
    231                 case 2:
    232                     text = convertToString((this->hudmode_ - 2) / 10);
    233                     break;
    234                 case 3:
    235                     text = "Press [Fire] to respawn";
    236                     break;
    237                 case 4:
    238                     text = "Game has ended";
    239                     break;
    240                 default:;
    241             }
    242 
    243             std::map<std::string, OrxonoxOverlay*>::const_iterator it = this->getHUD()->getOverlays().begin();
    244             for (; it != this->getHUD()->getOverlays().end(); ++it)
    245             {
    246                 if (it->second->isA(Class(OverlayText)) && it->second->getName() == "state")
    247                 {
    248                     OverlayText* overlay = dynamic_cast<OverlayText*>(it->second);
    249                     if (overlay)
    250                         overlay->setCaption(text);
    251                     break;
    252                 }
    253             }
    254         }
    255         // </hack>
    256     }
    257214}
  • code/trunk/src/orxonox/objects/worldentities/pawns/Spectator.h

    r2087 r2662  
    4242            virtual ~Spectator();
    4343
     44            void setConfigValues();
    4445            void registerVariables();
    4546            virtual void tick(float dt);
    4647
    4748            virtual void setPlayer(PlayerInfo* player);
    48             virtual void startLocalControl();
     49            virtual void startLocalHumanControl();
    4950
    5051            virtual void moveFrontBack(const Vector2& value);
     
    5657            virtual void rotateRoll(const Vector2& value);
    5758
    58             virtual void fire();
     59            virtual void fire(WeaponMode::Enum fireMode);
    5960            virtual void greet();
    6061
     
    6263            void changedGreeting();
    6364            void changedFlareVisibility();
    64             void updateHUD();
    6565
    6666            BillboardSet* greetingFlare_;
     
    6969
    7070            float speed_;
    71             float rotationSpeed_;
    7271
    7372            float yaw_;
     
    7574            float roll_;
    7675
    77             int hudmode_;
     76            Vector3 localVelocity_;
    7877    };
    7978}
  • code/trunk/src/orxonox/objects/worldentities/triggers/DistanceTrigger.cc

  • code/trunk/src/orxonox/objects/worldentities/triggers/DistanceTrigger.h

  • code/trunk/src/orxonox/objects/worldentities/triggers/PlayerTrigger.cc

    r2262 r2662  
    2828
    2929/**
    30     @file PlayerTrigger.cc
     30    @file
    3131    @brief
    32         Implementation of the PlayerTrigger class.
     32    Implementation of the PlayerTrigger class.
    3333*/
    3434
     
    3838#include "core/CoreIncludes.h"
    3939
    40 namespace orxonox {
    41 
     40namespace orxonox
     41{
    4242    /**
    4343    @brief
     
    4747    {
    4848        RegisterObject(PlayerTrigger);
    49        
     49
    5050        this->player_ = NULL;
    5151        this->isForPlayer_ = true;
    5252    }
    53    
     53
    5454    /**
    5555    @brief
     
    6666    void PlayerTrigger::XMLPort(Element& xmlelement, XMLPort::Mode mode)
    6767    {
    68         SUPER(PlayerTrigger, XMLPort, xmlelement, mode);
     68        SUPER(PlayerTrigger, XMLPort, xmlelement, mode);
    6969    }
    70 
    7170}
  • code/trunk/src/orxonox/objects/worldentities/triggers/PlayerTrigger.h

    r2262 r2662  
    2828
    2929/**
    30     @file PlayerTrigger.h
     30    @file
    3131    @brief
    32         Definition of the PlayerTrigger class.
     32    Definition of the PlayerTrigger class.
    3333*/
    3434
     
    4040#include "Trigger.h"
    4141
    42 namespace orxonox {
    43    
     42namespace orxonox
     43{
    4444    /**
    4545    @brief
     
    5050    class _OrxonoxExport PlayerTrigger : public Trigger
    5151    {
    52         public:
    53             PlayerTrigger(BaseObject* creator);
    54             virtual ~PlayerTrigger();
    55            
    56             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a PlayerTrigger object through XML.
     52    public:
     53        PlayerTrigger(BaseObject* creator);
     54        virtual ~PlayerTrigger();
     55       
     56        virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a PlayerTrigger object through XML.
     57       
     58        /**
     59        @brief Returns the player that triggered the PlayerTrigger.
     60        @return Returns a pointer to the ControllableEntity that triggered the PlayerTrigger.
     61        */
     62        inline ControllableEntity* getTriggeringPlayer(void) const
     63            { return this->player_; }
     64       
     65        /**
     66        @brief Checks whether the PlayerTrigger normally returns a ControllableEntity.
     67        @return Returns true if the PlayerTrigger normally returns a ControllableEntity.
     68        */
     69        inline bool isForPlayer(void) const
     70           { return this->isForPlayer_; }
    5771           
    58             /**
    59             @brief Returns the player that triggered the PlayerTrigger.
    60             @return Returns a pointer to the ControllableEntity that triggered the PlayerTrigger.
    61             */
    62             inline ControllableEntity* getTriggeringPlayer(void) const
    63                 { return this->player_; }
    64            
    65             /**
    66             @brief Checks whether the PlayerTrigger normally returns a ControllableEntity.
    67             @return Returns true if the PlayerTrigger normally returns a ControllableEntity.
    68             */
    69             inline bool isForPlayer(void) const
    70                { return this->isForPlayer_; }
    71            
    72         protected:
    73             virtual bool isTriggered(TriggerMode mode) = 0;
    74            
    75             /**
    76             @brief Set the player that triggered the PlayerTrigger. This is normally done by classes inheriting vom PlayerTrigger.
    77             @param player A pointer to the ControllableEntity that triggered the PlayerTrigger.
    78             */
    79             inline void setTriggeringPlayer(ControllableEntity* player)
    80                { this->player_ = player; }
     72    protected:
     73        virtual bool isTriggered(TriggerMode mode) = 0;
     74       
     75        /**
     76        @brief Set the player that triggered the PlayerTrigger. This is normally done by classes inheriting vom PlayerTrigger.
     77        @param player A pointer to the ControllableEntity that triggered the PlayerTrigger.
     78        */
     79        inline void setTriggeringPlayer(ControllableEntity* player)
     80           { this->player_ = player; }
    8181
    8282            /**
     
    8484            @param isForPlayer Should be true when the PlayerTrigger schould be set to normally be triggered by ControllableEntities, false if not.
    8585            */
    86             inline void setForPlayer(bool isForPlayer)
    87                { this->isForPlayer_ = isForPlayer; }
    88            
    89         private:
    90             ControllableEntity* player_; //!< The player that triggered the PlayerTrigger.
    91             bool isForPlayer_; //!< Is true when the PlayerTrigger schould be set to normally be triggered by ControllableEntities.
    92        
     86        inline void setForPlayer(bool isForPlayer)
     87           { this->isForPlayer_ = isForPlayer; }
     88       
     89    private:
     90        ControllableEntity* player_; //!< The player that triggered the PlayerTrigger.
     91        bool isForPlayer_; //!< Is true when the PlayerTrigger schould be set to normally be triggered by ControllableEntities.
     92   
    9393    };
    9494
  • code/trunk/src/orxonox/objects/worldentities/triggers/Trigger.cc

    r2261 r2662  
    3131
    3232#include <OgreBillboard.h>
     33#include <OgreBillboardSet.h>
    3334#include "util/Debug.h"
    3435#include "core/CoreIncludes.h"
    3536#include "core/ConsoleCommand.h"
    3637#include "core/XMLPort.h"
     38#include "core/Core.h"
    3739#include "objects/Scene.h"
    3840
     
    4446  CreateFactory(Trigger);
    4547
    46   Trigger::Trigger(BaseObject* creator) : PositionableEntity(creator)
     48  Trigger::Trigger(BaseObject* creator) : StaticEntity(creator)
    4749  {
    4850    RegisterObject(Trigger);
     
    6567//    this->bUpdating_ = false;
    6668
    67     if (this->getScene() && this->getScene()->getSceneManager())
     69    if (this->getScene() && Core::showsGraphics())
    6870    {
    6971      this->debugBillboard_.setBillboardSet(this->getScene()->getSceneManager(), "Examples/Flare", ColourValue(1.0, 0.0, 0.0), 1);
     
    7173
    7274      if (this->debugBillboard_.getBillboardSet())
    73         this->getNode()->attachObject(this->debugBillboard_.getBillboardSet());
     75          this->attachOgreObject(this->debugBillboard_.getBillboardSet());
    7476    }
    7577
     
    106108    if (!this->BaseObject::isActive())
    107109        return;
     110
     111    SUPER(Trigger, tick, dt);
    108112
    109113    bool newTriggered = this->isTriggered() ^ this->bInvertMode_;
  • code/trunk/src/orxonox/objects/worldentities/triggers/Trigger.h

    r2261 r2662  
    3636
    3737#include "objects/Tickable.h"
    38 #include "objects/worldentities/PositionableEntity.h"
     38#include "objects/worldentities/StaticEntity.h"
    3939#include "tools/BillboardSet.h"
    4040
     
    4848  };
    4949
    50   class _OrxonoxExport Trigger : public PositionableEntity, public Tickable
     50  class _OrxonoxExport Trigger : public StaticEntity, public Tickable
    5151  {
    5252    public:
Note: See TracChangeset for help on using the changeset viewer.