Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/SpaceRaceAI_HS16/src/orxonox/worldentities/pawns/Pawn.cc @ 11217

Last change on this file since 11217 was 11176, checked in by fvultier, 9 years ago

Added a debug console command that allows visualization of the weaponSlots.

  • Property svn:eol-style set to native
File size: 21.4 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      Simon Miescher
26 *
27 */
28
29#include "Pawn.h"
30
31#include <algorithm>
32
33#include "core/CoreIncludes.h"
34#include "core/GameMode.h"
35#include "core/XMLPort.h"
36#include "core/EventIncludes.h"
37#include "network/NetworkFunction.h"
38
39#include "infos/PlayerInfo.h"
40#include "controllers/Controller.h"
41#include "gametypes/Gametype.h"
42#include "graphics/ParticleSpawner.h"
43#include "worldentities/ExplosionChunk.h"
44#include "worldentities/ExplosionPart.h"
45#include "weaponsystem/WeaponSystem.h"
46#include "weaponsystem/WeaponSlot.h"
47#include "weaponsystem/WeaponPack.h"
48#include "weaponsystem/WeaponSet.h"
49#include "weaponsystem/Munition.h"
50#include "sound/WorldSound.h"
51#include "core/object/ObjectListIterator.h"
52
53#include "controllers/FormationController.h"
54
55namespace orxonox
56{
57    RegisterClass(Pawn);
58
59    SetConsoleCommand("Pawn", "debugDrawWeapons", &Pawn::consoleCommand_debugDrawWeapons).addShortcut();
60
61    Pawn::Pawn(Context* context)
62        : ControllableEntity(context)
63        , RadarViewable(this, static_cast<WorldEntity*>(this))
64    {
65        RegisterObject(Pawn);
66
67        this->bAlive_ = true;
68        this->bVulnerable_ = true;
69
70        this->health_ = 0;
71        this->maxHealth_ = 0;
72        this->initialHealth_ = 0;
73
74        this->shieldHealth_ = 0;
75        this->initialShieldHealth_ = 0;
76        this->maxShieldHealth_ = 100; //otherwise shield might increase to float_max
77        this->shieldAbsorption_ = 0.5;
78        this->shieldRechargeRate_ = 0;
79        this->shieldRechargeWaitTime_ = 1.0f;
80        this->shieldRechargeWaitCountdown_ = 0;
81
82        this->lastHitOriginator_ = nullptr;
83
84        // set damage multiplier to default value 1, meaning nominal damage
85        this->damageMultiplier_ = 1;
86
87        this->spawnparticleduration_ = 3.0f;
88
89        this->aimPosition_ = Vector3::ZERO;
90
91        //this->explosionPartList_ = nullptr;
92
93        if (GameMode::isMaster())
94        {
95            this->weaponSystem_ = new WeaponSystem(this->getContext());
96            this->weaponSystem_->setPawn(this);
97        }
98        else
99            this->weaponSystem_ = nullptr;
100
101        this->setRadarObjectColour(ColourValue::Red);
102        this->setRadarObjectShape(RadarViewable::Shape::Dot);
103
104        this->registerVariables();
105
106        this->isHumanShip_ = this->hasLocalController();
107
108        this->setSyncMode(ObjectDirection::Bidirectional); // needed to synchronise e.g. aimposition
109
110        if (GameMode::isMaster())
111        {
112            this->explosionSound_ = new WorldSound(this->getContext());
113            this->explosionSound_->setVolume(1.0f);
114        }
115        else
116        {
117            this->explosionSound_ = nullptr;
118        }
119    }
120
121    Pawn::~Pawn()
122    {
123        if (this->isInitialized())
124        {
125            if (this->weaponSystem_)
126                this->weaponSystem_->destroy();
127        }
128    }
129
130    void Pawn::XMLPort(Element& xmlelement, XMLPort::Mode mode)
131    {
132        SUPER(Pawn, XMLPort, xmlelement, mode);
133
134        XMLPortParam(Pawn, "health", setHealth, getHealth, xmlelement, mode).defaultValues(100);
135        XMLPortParam(Pawn, "maxhealth", setMaxHealth, getMaxHealth, xmlelement, mode).defaultValues(200);
136        XMLPortParam(Pawn, "initialhealth", setInitialHealth, getInitialHealth, xmlelement, mode).defaultValues(100);
137
138        XMLPortParam(Pawn, "shieldhealth", setShieldHealth, getShieldHealth, xmlelement, mode).defaultValues(0);
139        XMLPortParam(Pawn, "initialshieldhealth", setInitialShieldHealth, getInitialShieldHealth, xmlelement, mode).defaultValues(0);
140        XMLPortParam(Pawn, "maxshieldhealth", setMaxShieldHealth, getMaxShieldHealth, xmlelement, mode).defaultValues(100);
141        XMLPortParam(Pawn, "shieldabsorption", setShieldAbsorption, getShieldAbsorption, xmlelement, mode).defaultValues(0);
142
143        XMLPortParam(Pawn, "vulnerable", setVulnerable, isVulnerable, xmlelement, mode).defaultValues(true);
144
145        XMLPortParam(Pawn, "spawnparticlesource", setSpawnParticleSource, getSpawnParticleSource, xmlelement, mode);
146        XMLPortParam(Pawn, "spawnparticleduration", setSpawnParticleDuration, getSpawnParticleDuration, xmlelement, mode).defaultValues(3.0f);
147        XMLPortParam(Pawn, "explosionchunks", setExplosionChunks, getExplosionChunks, xmlelement, mode).defaultValues(0);
148
149        XMLPortObject(Pawn, WeaponSlot, "weaponslots", addWeaponSlot, getWeaponSlot, xmlelement, mode);
150        XMLPortObject(Pawn, WeaponSet, "weaponsets", addWeaponSet, getWeaponSet, xmlelement, mode);
151        XMLPortObject(Pawn, WeaponPack, "weaponpacks", addWeaponPackXML, getWeaponPack, xmlelement, mode);
152        XMLPortObject(Pawn, Munition, "munition", addMunitionXML, getMunitionXML, xmlelement, mode);
153
154        XMLPortObject(Pawn, ExplosionPart, "explosion", addExplosionPart, getExplosionPart, xmlelement, mode);
155        XMLPortParam(Pawn, "shieldrechargerate", setShieldRechargeRate, getShieldRechargeRate, xmlelement, mode).defaultValues(0);
156        XMLPortParam(Pawn, "shieldrechargewaittime", setShieldRechargeWaitTime, getShieldRechargeWaitTime, xmlelement, mode).defaultValues(1.0f);
157
158        XMLPortParam(Pawn, "explosionSound",  setExplosionSound,  getExplosionSound,  xmlelement, mode);
159
160        XMLPortParam ( RadarViewable, "radarname", setRadarName, getRadarName, xmlelement, mode );
161    }
162
163    void Pawn::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
164    {
165        SUPER(Pawn, XMLEventPort, xmlelement, mode);
166
167        XMLPortEventState(Pawn, BaseObject, "vulnerability", setVulnerable, xmlelement, mode);
168    }
169
170    void Pawn::registerVariables()
171    {
172        registerVariable(this->bAlive_,            VariableDirection::ToClient);
173        registerVariable(this->bVulnerable_,       VariableDirection::ToClient);
174        registerVariable(this->health_,            VariableDirection::ToClient);
175        registerVariable(this->maxHealth_,         VariableDirection::ToClient);
176        registerVariable(this->shieldHealth_,      VariableDirection::ToClient);
177        registerVariable(this->maxShieldHealth_,   VariableDirection::ToClient);
178        registerVariable(this->shieldAbsorption_,  VariableDirection::ToClient);
179        registerVariable(this->aimPosition_,       VariableDirection::ToServer);  // For the moment this variable gets only transfered to the server
180    }
181
182    void Pawn::tick(float dt)
183    {
184        //BigExplosion* chunk = new BigExplosion(this->getContext());
185        SUPER(Pawn, tick, dt);
186
187        // Recharge the shield
188        // TODO: use the existing timer functions instead
189        if(this->shieldRechargeWaitCountdown_ > 0)
190        {
191            this->decreaseShieldRechargeCountdownTime(dt);
192        }
193        else
194        {
195            this->addShieldHealth(this->getShieldRechargeRate() * dt);
196            this->resetShieldRechargeCountdown();
197        }
198
199        if (GameMode::isMaster())
200        {
201            if (this->health_ <= 0 && bAlive_)
202            {
203                this->fireEvent(); // Event to notify anyone who wants to know about the death.
204                this->death();
205            }
206        }
207    }
208
209    void Pawn::preDestroy()
210    {
211        // yay, multiple inheritance!
212        this->ControllableEntity::preDestroy();
213        this->PickupCarrier::preDestroy();
214    }
215
216    void Pawn::setPlayer(PlayerInfo* player)
217    {
218        ControllableEntity::setPlayer(player);
219
220        if (this->getGametype())
221            this->getGametype()->playerStartsControllingPawn(player, this);
222    }
223
224    void Pawn::removePlayer()
225    {
226        if (this->getGametype())
227            this->getGametype()->playerStopsControllingPawn(this->getPlayer(), this);
228
229        ControllableEntity::removePlayer();
230    }
231
232
233    void Pawn::setHealth(float health)
234    {
235        this->health_ = std::min(health, this->maxHealth_); //Health can't be set to a value bigger than maxHealth, otherwise it will be reduced at first hit
236    }
237
238    void Pawn::setShieldHealth(float shieldHealth)
239    {
240        this->shieldHealth_ = std::min(shieldHealth, this->maxShieldHealth_);
241    }
242
243    void Pawn::setMaxShieldHealth(float maxshieldhealth)
244    {
245        this->maxShieldHealth_ = maxshieldhealth;
246    }
247
248    void Pawn::setShieldRechargeRate(float shieldRechargeRate)
249    {
250        this->shieldRechargeRate_ = shieldRechargeRate;
251    }
252
253    void Pawn::setShieldRechargeWaitTime(float shieldRechargeWaitTime)
254    {
255        this->shieldRechargeWaitTime_ = shieldRechargeWaitTime;
256    }
257
258    void Pawn::decreaseShieldRechargeCountdownTime(float dt)
259    {
260        this->shieldRechargeWaitCountdown_ -= dt;
261    }
262
263    void Pawn::changedVulnerability()
264    {
265
266    }
267
268    void Pawn::damage(float damage, float healthdamage, float shielddamage, Pawn* originator, const btCollisionShape* cs)
269    {
270        // A pawn can only get damaged if it is vulnerable
271        if (!isVulnerable())
272        {
273            return;
274        }
275
276        // Applies multiplier given by the DamageBoost Pickup.
277        if (originator)
278            damage *= originator->getDamageMultiplier();
279
280        if (this->getGametype() && this->getGametype()->allowPawnDamage(this, originator))
281        {
282            // Health-damage cannot be absorbed by shields.
283            // Shield-damage only reduces shield health.
284            // Normal damage can be (partially) absorbed by shields.
285
286            if (shielddamage >= this->getShieldHealth())
287            {
288                this->setShieldHealth(0);
289                this->setHealth(this->health_ - (healthdamage + damage));
290            }
291            else
292            {
293                this->setShieldHealth(this->shieldHealth_ - shielddamage);
294
295                // remove remaining shieldAbsorpton-Part of damage from shield
296                shielddamage = damage * this->shieldAbsorption_;
297                shielddamage = std::min(this->getShieldHealth(),shielddamage);
298                this->setShieldHealth(this->shieldHealth_ - shielddamage);
299
300                // set remaining damage to health
301                this->setHealth(this->health_ - (damage - shielddamage) - healthdamage);
302            }
303
304            this->lastHitOriginator_ = originator;
305        }
306    }
307
308// TODO: Still valid?
309/* HIT-Funktionen
310    Die hit-Funktionen muessen auch in src/orxonox/controllers/Controller.h angepasst werden! (Visuelle Effekte)
311
312*/
313    void Pawn::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
314    {
315        if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
316        {
317            this->damage(damage, healthdamage, shielddamage, originator, cs);
318            this->setVelocity(this->getVelocity() + force);
319        }
320    }
321
322    void Pawn::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
323    {
324        if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
325        {
326            this->damage(damage, healthdamage, shielddamage, originator, cs);
327
328            if ( this->getController() )
329                this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
330        }
331    }
332
333    void Pawn::kill()
334    {
335        this->damage(this->health_);
336        this->death();
337    }
338
339    void Pawn::spawneffect()
340    {
341        // play spawn effect
342        if (!this->spawnparticlesource_.empty())
343        {
344            ParticleSpawner* effect = new ParticleSpawner(this->getContext());
345            effect->setPosition(this->getPosition());
346            effect->setOrientation(this->getOrientation());
347            effect->setDestroyAfterLife(true);
348            effect->setSource(this->spawnparticlesource_);
349            effect->setLifetime(this->spawnparticleduration_);
350        }
351    }
352
353    void Pawn::death()
354    {
355        this->setHealth(1);
356        if (this->getGametype() && this->getGametype()->allowPawnDeath(this, this->lastHitOriginator_))
357        {
358            // Set bAlive_ to false and wait for destroyLater() to do the destruction
359            this->bAlive_ = false;
360            this->destroyLater();
361
362            this->setDestroyWhenPlayerLeft(false);
363
364            if (this->getGametype())
365                this->getGametype()->pawnKilled(this, this->lastHitOriginator_);
366
367            if (this->getPlayer() && this->getPlayer()->getControllableEntity() == this)
368            {
369                // Start to control a new entity if you're the master of a formation
370                if(this->hasSlaves())
371                {
372                    Controller* slave = this->getSlave();
373                    ControllableEntity* entity = slave->getControllableEntity();
374
375
376                    if(!entity->hasHumanController())
377                    {
378                        // delete the AIController // <-- TODO: delete? nothing is deleted here... should we delete the controller?
379                        slave->setControllableEntity(nullptr);
380
381                        // set a new master within the formation
382                        orxonox_cast<FormationController*>(this->getController())->setNewMasterWithinFormation(orxonox_cast<FormationController*>(slave));
383
384                        // start to control a slave
385                        this->getPlayer()->startControl(entity);
386                    }
387                    else
388                    {
389                        this->getPlayer()->stopControl();
390                    }
391
392                }
393                else
394                {
395                    this->getPlayer()->stopControl();
396                }
397            }
398            if (GameMode::isMaster())
399            {
400                this->goWithStyle();
401            }
402        }
403    }
404    void Pawn::goWithStyle()
405    {
406
407        this->bAlive_ = false;
408        this->setDestroyWhenPlayerLeft(false);
409
410        while(!explosionPartList_.empty())
411        {
412            explosionPartList_.back()->setPosition(this->getPosition());
413            explosionPartList_.back()->setVelocity(this->getVelocity());
414            explosionPartList_.back()->setOrientation(this->getOrientation());
415            explosionPartList_.back()->Explode();
416            explosionPartList_.pop_back();
417        }
418
419        for (unsigned int i = 0; i < this->numexplosionchunks_; ++i)
420        {
421            ExplosionChunk* chunk = new ExplosionChunk(this->getContext());
422            chunk->setPosition(this->getPosition());
423        }
424
425        this->explosionSound_->setPosition(this->getPosition());
426        this->explosionSound_->play();
427    }
428
429    /**
430    @brief
431        Check whether the Pawn has a @ref orxonox::WeaponSystem and fire it with the specified firemode if it has one.
432    */
433
434    void Pawn::fired(unsigned int firemode)
435    {
436        if (this->weaponSystem_)
437            this->weaponSystem_->fire(firemode);
438    }
439
440    void Pawn::postSpawn()
441    {
442        this->setHealth(this->initialHealth_);
443        if (GameMode::isMaster())
444            this->spawneffect();
445    }
446
447
448    void Pawn::addExplosionPart(ExplosionPart* ePart)
449    {this->explosionPartList_.push_back(ePart);}
450
451
452    ExplosionPart * Pawn::getExplosionPart()
453    {return this->explosionPartList_.back();}
454
455
456
457    /* WeaponSystem:
458    *   functions load Slot, Set, Pack from XML and make sure all parent-pointers are set.
459    *   with setWeaponPack you can not just load a Pack from XML but if a Pack already exists anywhere, you can attach it.
460    *       --> e.g. Pickup-Items
461    */
462    void Pawn::addWeaponSlot(WeaponSlot * wSlot)
463    {
464        this->attach(wSlot);
465        if (this->weaponSystem_)
466            this->weaponSystem_->addWeaponSlot(wSlot);
467    }
468
469    WeaponSlot * Pawn::getWeaponSlot(unsigned int index) const
470    {
471        if (this->weaponSystem_)
472            return this->weaponSystem_->getWeaponSlot(index);
473        else
474            return nullptr;
475    }
476
477    void Pawn::addWeaponSet(WeaponSet * wSet)
478    {
479        if (this->weaponSystem_)
480            this->weaponSystem_->addWeaponSet(wSet);
481    }
482
483    WeaponSet * Pawn::getWeaponSet(unsigned int index) const
484    {
485        if (this->weaponSystem_)
486            return this->weaponSystem_->getWeaponSet(index);
487        else
488            return nullptr;
489    }
490
491    void Pawn::addWeaponPack(WeaponPack * wPack)
492    {
493        if (this->weaponSystem_)
494        {
495            this->weaponSystem_->addWeaponPack(wPack);
496            this->addedWeaponPack(wPack);
497        }
498    }
499
500    void Pawn::addWeaponPackXML(WeaponPack * wPack)
501    {
502        if (this->weaponSystem_)
503        {
504            if (!this->weaponSystem_->addWeaponPack(wPack))
505                wPack->destroy();
506            else
507                this->addedWeaponPack(wPack);
508        }
509    }
510
511    WeaponPack * Pawn::getWeaponPack(unsigned int index) const
512    {
513        if (this->weaponSystem_)
514            return this->weaponSystem_->getWeaponPack(index);
515        else
516            return nullptr;
517    }
518
519    void Pawn::addMunitionXML(Munition* munition)
520    {
521        if (this->weaponSystem_ && munition)
522        {
523            this->weaponSystem_->addMunition(munition);
524        }
525    }
526
527    Munition* Pawn::getMunitionXML() const
528    {
529        return nullptr;
530    }
531
532    Munition* Pawn::getMunition(SubclassIdentifier<Munition> * identifier)
533    {
534        if (weaponSystem_)
535        {
536            return weaponSystem_->getMunition(identifier);
537        }
538
539        return nullptr;
540    }
541
542    //Tell the Map (RadarViewable), if this is a playership
543    void Pawn::startLocalHumanControl()
544    {
545//        SUPER(ControllableEntity, startLocalHumanControl());
546        ControllableEntity::startLocalHumanControl();
547        this->isHumanShip_ = true;
548    }
549
550    void Pawn::changedVisibility(void)
551    {
552        SUPER(Pawn, changedVisibility);
553
554        // enable proper radarviewability when the visibility is changed
555        this->RadarViewable::settingsChanged();
556    }
557
558
559    // A function to check if this pawn's controller is the master of any formationcontroller
560    bool Pawn::hasSlaves()
561    {
562        for (FormationController* controller : ObjectList<FormationController>())
563        {
564            // checks if the pawn's controller has a slave
565            if (this->hasHumanController() && controller->getMaster() == this->getPlayer()->getController())
566                return true;
567        }
568        return false;
569    }
570
571    // A function that returns a slave of the pawn's controller
572    Controller* Pawn::getSlave(){
573        for (FormationController* controller : ObjectList<FormationController>())
574        {
575            if (this->hasHumanController() && controller->getMaster() == this->getPlayer()->getController())
576                return controller->getController();
577        }
578        return nullptr;
579    }
580
581
582    void Pawn::setExplosionSound(const std::string &explosionSound)
583    {
584        if(explosionSound_ )
585            explosionSound_->setSource(explosionSound);
586        else
587            assert(0); // This should never happen, because soundpointer is only available on master
588    }
589
590    const std::string& Pawn::getExplosionSound()
591    {
592        if( explosionSound_ )
593            return explosionSound_->getSource();
594        else
595            assert(0);
596        return BLANKSTRING;
597    }
598
599    void Pawn::drawWeapons(bool bDraw)
600    {
601        if (bDraw)
602        {
603            std::vector<WeaponSlot*> weaponSlots = weaponSystem_->getAllWeaponSlots();
604            int numWeaponSlots = weaponSlots.size();
605            Vector3 slotPosition = Vector3::ZERO;
606            Quaternion slotOrientation = Quaternion::IDENTITY;
607            Model* slotModel = nullptr;
608
609            for (int i = 0; i < numWeaponSlots; ++i)
610            {
611                slotPosition = weaponSlots.at(i)->getPosition();
612                slotOrientation = weaponSlots.at(i)->getOrientation();
613                slotModel = new Model(this->getContext());
614                slotModel->setMeshSource("Coordinates.mesh");
615                slotModel->setScale(3.0f);
616                slotModel->setOrientation(slotOrientation);
617                slotModel->setPosition(slotPosition);
618
619                this->attach(slotModel);
620                debugWeaponSlotModels_.push_back(slotModel);
621            }
622        }
623        else
624        {
625            // delete all debug models
626            for(Model* model : debugWeaponSlotModels_) 
627            {
628                model->destroy();
629            }
630            debugWeaponSlotModels_.clear();
631        }
632    }
633
634    /*static*/ void Pawn::consoleCommand_debugDrawWeapons(bool bDraw)
635    {
636        if (bDraw)
637        {
638            orxout() << "WeaponSlot visualization enabled." << endl;
639        }
640        else
641        {
642            orxout() << "WeaponSlot visualization disabled." << endl;
643        }
644
645        ObjectList<Pawn> pawnList;
646        for (ObjectListIterator<Pawn> it = pawnList.begin(); it != pawnList.end(); ++it)
647        {
648            it->drawWeapons(bDraw);
649        }
650    }
651}
Note: See TracBrowser for help on using the repository browser.