Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/3DPacman_FS19/src/orxonox/worldentities/pawns/Pawn.cc @ 12206

Last change on this file since 12206 was 12028, checked in by merholzl, 6 years ago

added scriptable controller

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