Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ScriptableController_HS17/src/orxonox/worldentities/pawns/Pawn.cc @ 11843

Last change on this file since 11843 was 11606, checked in by kohlia, 7 years ago

Pawn killing works too now

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