Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/modularships/src/orxonox/worldentities/pawns/Pawn.cc @ 10036

Last change on this file since 10036 was 10023, checked in by noep, 11 years ago

ShipParts can "die" and detach the corresponding Entity while doing so. Issue: The Entity being detached while a hit on a collisionshape is being handled causes a runtime-error.

  • Property svn:eol-style set to native
File size: 22.3 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 "network/NetworkFunction.h"
37
38#include "infos/PlayerInfo.h"
39#include "controllers/Controller.h"
40#include "gametypes/Gametype.h"
41#include "graphics/ParticleSpawner.h"
42#include "worldentities/ExplosionChunk.h"
43#include "worldentities/BigExplosion.h"
44#include "weaponsystem/WeaponSystem.h"
45#include "weaponsystem/WeaponSlot.h"
46#include "weaponsystem/WeaponPack.h"
47#include "weaponsystem/WeaponSet.h"
48#include "sound/WorldSound.h"
49
50#include "controllers/FormationController.h"
51
52#include "collisionshapes/WorldEntityCollisionShape.h"
53#include <BulletCollision/CollisionShapes/btCollisionShape.h>
54#include <BulletCollision/CollisionShapes/btCompoundShape.h>
55#include "graphics/Model.h"
56
57
58namespace orxonox
59{
60    RegisterClass(Pawn);
61
62    Pawn::Pawn(Context* context)
63        : ControllableEntity(context)
64        , RadarViewable(this, static_cast<WorldEntity*>(this))
65    {
66        RegisterObject(Pawn);
67
68        this->bAlive_ = true;
69        this->bReload_ = false;
70
71        this->health_ = 0;
72        this->maxHealth_ = 0;
73        this->initialHealth_ = 0;
74
75        this->shieldHealth_ = 0;
76        this->initialShieldHealth_ = 0;
77        this->maxShieldHealth_ = 100; //otherwise shield might increase to float_max
78        this->shieldAbsorption_ = 0.5;
79
80        this->reloadRate_ = 0;
81        this->reloadWaitTime_ = 1.0f;
82        this->reloadWaitCountdown_ = 0;
83
84        this->lastHitOriginator_ = 0;
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        if (GameMode::isMaster())
94        {
95            this->weaponSystem_ = new WeaponSystem(this->getContext());
96            this->weaponSystem_->setPawn(this);
97        }
98        else
99            this->weaponSystem_ = 0;
100
101        this->setRadarObjectColour(ColourValue::Red);
102        this->setRadarObjectShape(RadarViewable::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_ = 0;
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, "spawnparticlesource", setSpawnParticleSource, getSpawnParticleSource, xmlelement, mode);
144        XMLPortParam(Pawn, "spawnparticleduration", setSpawnParticleDuration, getSpawnParticleDuration, xmlelement, mode).defaultValues(3.0f);
145        XMLPortParam(Pawn, "explosionchunks", setExplosionChunks, getExplosionChunks, xmlelement, mode).defaultValues(7);
146
147        XMLPortObject(Pawn, WeaponSlot, "weaponslots", addWeaponSlot, getWeaponSlot, xmlelement, mode);
148        XMLPortObject(Pawn, WeaponSet, "weaponsets", addWeaponSet, getWeaponSet, xmlelement, mode);
149        XMLPortObject(Pawn, WeaponPack, "weapons", addWeaponPackXML, getWeaponPack, xmlelement, mode);
150
151        XMLPortParam(Pawn, "reloadrate", setReloadRate, getReloadRate, xmlelement, mode).defaultValues(0);
152        XMLPortParam(Pawn, "reloadwaittime", setReloadWaitTime, getReloadWaitTime, xmlelement, mode).defaultValues(1.0f);
153
154        XMLPortParam(Pawn, "explosionSound",  setExplosionSound,  getExplosionSound,  xmlelement, mode);
155
156        XMLPortParam ( RadarViewable, "radarname", setRadarName, getRadarName, xmlelement, mode );
157    }
158
159    void Pawn::registerVariables()
160    {
161        registerVariable(this->bAlive_,           VariableDirection::ToClient);
162        registerVariable(this->health_,           VariableDirection::ToClient);
163        registerVariable(this->maxHealth_,        VariableDirection::ToClient);
164        registerVariable(this->shieldHealth_,     VariableDirection::ToClient);
165        registerVariable(this->maxShieldHealth_,  VariableDirection::ToClient);
166        registerVariable(this->shieldAbsorption_, VariableDirection::ToClient);
167        registerVariable(this->bReload_,          VariableDirection::ToServer);
168        registerVariable(this->aimPosition_,      VariableDirection::ToServer);  // For the moment this variable gets only transfered to the server
169    }
170
171    void Pawn::tick(float dt)
172    {
173        SUPER(Pawn, tick, dt);
174
175        this->bReload_ = false;
176
177        // TODO: use the existing timer functions instead
178        if(this->reloadWaitCountdown_ > 0)
179        {
180            this->decreaseReloadCountdownTime(dt);
181        }
182        else
183        {
184            this->addShieldHealth(this->getReloadRate() * dt);
185            this->resetReloadCountdown();
186        }
187
188        if (GameMode::isMaster())
189        {
190            if (this->health_ <= 0 && bAlive_)
191            {
192                this->fireEvent(); // Event to notify anyone who wants to know about the death.
193                this->death();
194            }
195        }
196    }
197
198    void Pawn::preDestroy()
199    {
200        // yay, multiple inheritance!
201        this->ControllableEntity::preDestroy();
202        this->PickupCarrier::preDestroy();
203    }
204
205    void Pawn::setPlayer(PlayerInfo* player)
206    {
207        ControllableEntity::setPlayer(player);
208
209        if (this->getGametype())
210            this->getGametype()->playerStartsControllingPawn(player, this);
211    }
212
213    void Pawn::removePlayer()
214    {
215        if (this->getGametype())
216            this->getGametype()->playerStopsControllingPawn(this->getPlayer(), this);
217
218        ControllableEntity::removePlayer();
219    }
220
221
222    void Pawn::setHealth(float health)
223    {
224        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
225    }
226
227    void Pawn::setShieldHealth(float shieldHealth)
228    {
229        this->shieldHealth_ = std::min(shieldHealth, this->maxShieldHealth_);
230    }
231
232    void Pawn::setMaxShieldHealth(float maxshieldhealth)
233    {
234        this->maxShieldHealth_ = maxshieldhealth;
235    }
236
237    void Pawn::setReloadRate(float reloadrate)
238    {
239        this->reloadRate_ = reloadrate;
240    }
241
242    void Pawn::setReloadWaitTime(float reloadwaittime)
243    {
244        this->reloadWaitTime_ = reloadwaittime;
245    }
246
247    void Pawn::decreaseReloadCountdownTime(float dt)
248    {
249        this->reloadWaitCountdown_ -= dt;
250    }
251
252    void Pawn::damage(float damage, float healthdamage, float shielddamage, Pawn* originator, const btCollisionShape* cs)
253    {
254        //FIXME: (noep) remove debug
255        //orxout() << "damage(): Collision detected on " << this->getName() << ", btCS*: " << cs << endl;
256
257        //int collisionShapeIndex = this->isMyCollisionShape(cs);
258        //orxout() << collisionShapeIndex << endl;
259
260        // Applies multiplier given by the DamageBoost Pickup.
261        if (originator)
262            damage *= originator->getDamageMultiplier();
263
264        if (this->getGametype() && this->getGametype()->allowPawnDamage(this, originator))
265        {
266            if (shielddamage >= this->getShieldHealth())
267            {
268                this->setShieldHealth(0);
269                this->setHealth(this->health_ - (healthdamage + damage));
270            }
271            else
272            {
273                this->setShieldHealth(this->shieldHealth_ - shielddamage);
274
275                // remove remaining shieldAbsorpton-Part of damage from shield
276                shielddamage = damage * this->shieldAbsorption_;
277                shielddamage = std::min(this->getShieldHealth(),shielddamage);
278                this->setShieldHealth(this->shieldHealth_ - shielddamage);
279
280                // set remaining damage to health
281                this->setHealth(this->health_ - (damage - shielddamage) - healthdamage);
282            }
283
284            this->lastHitOriginator_ = originator;
285        }
286    }
287
288// TODO: Still valid?
289/* HIT-Funktionen
290    Die hit-Funktionen muessen auch in src/orxonox/controllers/Controller.h angepasst werden! (Visuelle Effekte)
291
292*/
293    void Pawn::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
294    {
295        if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
296        {
297            this->damage(damage, healthdamage, shielddamage, originator, cs);
298            this->setVelocity(this->getVelocity() + force);
299        }
300    }
301
302    void Pawn::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
303    {
304        if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
305        {
306            this->damage(damage, healthdamage, shielddamage, originator, cs);
307
308            if ( this->getController() )
309                this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
310        }
311    }
312
313
314    void Pawn::kill()
315    {
316        this->damage(this->health_);
317        this->death();
318    }
319
320    void Pawn::spawneffect()
321    {
322        // play spawn effect
323        if (!this->spawnparticlesource_.empty())
324        {
325            ParticleSpawner* effect = new ParticleSpawner(this->getContext());
326            effect->setPosition(this->getPosition());
327            effect->setOrientation(this->getOrientation());
328            effect->setDestroyAfterLife(true);
329            effect->setSource(this->spawnparticlesource_);
330            effect->setLifetime(this->spawnparticleduration_);
331        }
332    }
333
334
335    void Pawn::death()
336    {
337        this->setHealth(1);
338        if (this->getGametype() && this->getGametype()->allowPawnDeath(this, this->lastHitOriginator_))
339        {
340            // Set bAlive_ to false and wait for PawnManager to do the destruction
341            this->bAlive_ = false;
342
343            this->setDestroyWhenPlayerLeft(false);
344
345            if (this->getGametype())
346                this->getGametype()->pawnKilled(this, this->lastHitOriginator_);
347
348            if (this->getPlayer() && this->getPlayer()->getControllableEntity() == this)
349            {
350                // Start to control a new entity if you're the master of a formation
351                if(this->hasSlaves())
352                {
353                    Controller* slave = this->getSlave();
354                    ControllableEntity* entity = slave->getControllableEntity();
355
356
357                    if(!entity->hasHumanController())
358                    {
359                        // delete the AIController // <-- TODO: delete? nothing is deleted here... should we delete the controller?
360                        slave->setControllableEntity(0);
361
362                        // set a new master within the formation
363                        orxonox_cast<FormationController*>(this->getController())->setNewMasterWithinFormation(orxonox_cast<FormationController*>(slave));
364
365                        // start to control a slave
366                        this->getPlayer()->startControl(entity);
367                    }
368                    else
369                    {
370                        this->getPlayer()->stopControl();
371                    }
372
373                }
374                else
375                {
376                    this->getPlayer()->stopControl();
377                }
378            }
379            if (GameMode::isMaster())
380            {
381//                this->deathEffect();
382                this->goWithStyle();
383            }
384        }
385    }
386    void Pawn::goWithStyle()
387    {
388        this->bAlive_ = false;
389        this->setDestroyWhenPlayerLeft(false);
390
391        BigExplosion* chunk = new BigExplosion(this->getContext());
392        chunk->setPosition(this->getPosition());
393        chunk->setVelocity(this->getVelocity());
394
395        this->explosionSound_->setPosition(this->getPosition());
396        this->explosionSound_->play();
397    }
398    void Pawn::deatheffect()
399    {
400        // play death effect
401        {
402            ParticleSpawner* effect = new ParticleSpawner(this->getContext());
403            effect->setPosition(this->getPosition());
404            effect->setOrientation(this->getOrientation());
405            effect->setDestroyAfterLife(true);
406            effect->setSource("Orxonox/explosion2b");
407            effect->setLifetime(4.0f);
408        }
409        {
410            ParticleSpawner* effect = new ParticleSpawner(this->getContext());
411            effect->setPosition(this->getPosition());
412            effect->setOrientation(this->getOrientation());
413            effect->setDestroyAfterLife(true);
414            effect->setSource("Orxonox/smoke6");
415            effect->setLifetime(4.0f);
416        }
417        {
418            ParticleSpawner* effect = new ParticleSpawner(this->getContext());
419            effect->setPosition(this->getPosition());
420            effect->setOrientation(this->getOrientation());
421            effect->setDestroyAfterLife(true);
422            effect->setSource("Orxonox/sparks");
423            effect->setLifetime(4.0f);
424        }
425        for (unsigned int i = 0; i < this->numexplosionchunks_; ++i)
426        {
427            ExplosionChunk* chunk = new ExplosionChunk(this->getContext());
428            chunk->setPosition(this->getPosition());
429        }
430    }
431
432    void Pawn::fired(unsigned int firemode)
433    {
434        if (this->weaponSystem_)
435            this->weaponSystem_->fire(firemode);
436    }
437
438    void Pawn::reload()
439    {
440        this->bReload_ = true;
441    }
442
443    void Pawn::postSpawn()
444    {
445        this->setHealth(this->initialHealth_);
446        if (GameMode::isMaster())
447            this->spawneffect();
448    }
449
450    /* WeaponSystem:
451    *   functions load Slot, Set, Pack from XML and make sure all parent-pointers are set.
452    *   with setWeaponPack you can not just load a Pack from XML but if a Pack already exists anywhere, you can attach it.
453    *       --> e.g. Pickup-Items
454    */
455    void Pawn::addWeaponSlot(WeaponSlot * wSlot)
456    {
457        this->attach(wSlot);
458        if (this->weaponSystem_)
459            this->weaponSystem_->addWeaponSlot(wSlot);
460    }
461
462    WeaponSlot * Pawn::getWeaponSlot(unsigned int index) const
463    {
464        if (this->weaponSystem_)
465            return this->weaponSystem_->getWeaponSlot(index);
466        else
467            return 0;
468    }
469
470    void Pawn::addWeaponSet(WeaponSet * wSet)
471    {
472        if (this->weaponSystem_)
473            this->weaponSystem_->addWeaponSet(wSet);
474    }
475
476    WeaponSet * Pawn::getWeaponSet(unsigned int index) const
477    {
478        if (this->weaponSystem_)
479            return this->weaponSystem_->getWeaponSet(index);
480        else
481            return 0;
482    }
483
484    void Pawn::addWeaponPack(WeaponPack * wPack)
485    {
486        if (this->weaponSystem_)
487        {
488            this->weaponSystem_->addWeaponPack(wPack);
489            this->addedWeaponPack(wPack);
490        }
491    }
492
493    void Pawn::addWeaponPackXML(WeaponPack * wPack)
494    {
495        if (this->weaponSystem_)
496        {
497            if (!this->weaponSystem_->addWeaponPack(wPack))
498                wPack->destroy();
499            else
500                this->addedWeaponPack(wPack);
501        }
502    }
503
504    WeaponPack * Pawn::getWeaponPack(unsigned int index) const
505    {
506        if (this->weaponSystem_)
507            return this->weaponSystem_->getWeaponPack(index);
508        else
509            return 0;
510    }
511
512    //Tell the Map (RadarViewable), if this is a playership
513    void Pawn::startLocalHumanControl()
514    {
515//        SUPER(ControllableEntity, changedPlayer());
516        ControllableEntity::startLocalHumanControl();
517        this->isHumanShip_ = true;
518    }
519
520    void Pawn::changedVisibility(void)
521    {
522        SUPER(Pawn, changedVisibility);
523
524        // enable proper radarviewability when the visibility is changed
525        this->RadarViewable::settingsChanged();
526    }
527
528
529    // A function to check if this pawn's controller is the master of any formationcontroller
530    bool Pawn::hasSlaves()
531    {
532        for (ObjectList<FormationController>::iterator it =
533             ObjectList<FormationController>::begin();
534             it != ObjectList<FormationController>::end(); ++it )
535        {
536            // checks if the pawn's controller has a slave
537            if (this->hasHumanController() && it->getMaster() == this->getPlayer()->getController())
538                return true;
539        }
540        return false;
541    }
542
543    // A function that returns a slave of the pawn's controller
544    Controller* Pawn::getSlave(){
545        for (ObjectList<FormationController>::iterator it =
546                ObjectList<FormationController>::begin();
547                it != ObjectList<FormationController>::end(); ++it )
548        {
549            if (this->hasHumanController() && it->getMaster() == this->getPlayer()->getController())
550                return it->getController();
551        }
552        return 0;
553    }
554
555
556    void Pawn::setExplosionSound(const std::string &explosionSound)
557    {
558        if(explosionSound_ )
559            explosionSound_->setSource(explosionSound);
560        else
561            assert(0); // This should never happen, because soundpointer is only available on master
562    }
563
564    const std::string& Pawn::getExplosionSound()
565    {
566        if( explosionSound_ )
567            return explosionSound_->getSource();
568        else
569            assert(0);
570        return BLANKSTRING;
571    }
572
573
574    int Pawn::isMyCollisionShape(const btCollisionShape* cs)
575    {
576        // This entities WECS
577        WorldEntityCollisionShape* ownWECS = this->getWorldEntityCollisionShape();
578
579        // e.g. "Box 4: Searching for CS 0x1ad49200"
580        orxout() << this->getName() << ": Searching for btCS* " << cs << endl;
581        // e.g. "Box 4 is WorldEntityCollisionShape 0x126dd060"
582        orxout() << "  " << this->getName() << " is WorldEntityCollisionShape* " << ownWECS << endl;
583        // e.g. "Box 4 is WorldEntity 0x126dd060"
584        orxout() << "  " << this->getName() << " is WorldEntity* " << this << endl;
585        // e.g. "Box 4 is objectID 943"
586        orxout() << "  " << this->getName() << " is objectID " << this->getObjectID() << endl;
587
588        // List all attached Objects
589        orxout() << "  " << this->getName() << " has the following Objects attached:" << endl;
590        for (int i=0; i<50; i++)
591        {
592            if (this->getAttachedObject(i)==NULL)
593                break;
594            orxout() << " " << i << ": " << this->getAttachedObject(i) << " (" << this->getAttachedObject(i)->getName() << ")";
595            if(!orxonox_cast<Model*>(this->getAttachedObject(i)))
596                orxout() << " (SE)";
597            orxout() << endl;
598        }
599
600
601        // print child shapes of this WECS
602        printBtChildShapes((btCompoundShape*)(ownWECS->getCollisionShape()), 2, 0);
603
604        int temp = entityOfCollisionShape(cs);
605        if (temp==0)
606            orxout() << this->getName() << " has been hit on it's main body." << endl;
607        else
608            orxout() << this->getName() << " has been hit on the attached entity no. " << temp << endl;
609
610        // end
611        return -1;
612    }
613
614    void Pawn::printBtChildShapes(btCompoundShape* cs, int indent, int subshape)
615    {
616        // e.g. "  Childshape 1 (WECS 0x126dc8c0) has 2 childshapes:"
617        printSpaces(indent);  orxout() << "Childshape " << subshape << " (btCS* " << cs << ") has " << cs->getNumChildShapes() << " childshapes:" << endl;
618
619        for (int i=0; i < cs->getNumChildShapes(); i++)
620        {
621            printSpaces(indent+2);  orxout() << "- " << i << " - - -" << endl;
622
623            // For each childshape, print: (as long as it's not another CompoundCollisionShape)
624            if (!orxonox_cast<btCompoundShape*>(cs->getChildShape(i)))
625            {
626                // pointer to the btCollisionShape
627                printSpaces(indent+2);  orxout() << "btCollisionShape*: " << cs->getChildShape(i) << endl;
628
629                // pointer to the btCollisionShape
630                printSpaces(indent+2);  orxout() << "m_userPointer*: " << cs->getChildShape(i)->getUserPointer() << " (name_: " << ((BaseObject*)(cs->getChildShape(i)->getUserPointer()))->getName() << ")" << endl;
631            }
632
633            // if the childshape is a CompoundCollisionShape, print its children.
634            if (cs->getChildShape(i)->isCompound())
635                printBtChildShapes((btCompoundShape*)(cs->getChildShape(i)), indent+2, i);
636
637        }
638    }
639
640    int Pawn::entityOfCollisionShape(const btCollisionShape* cs)
641    {
642        btCompoundShape* ownBtCS = (btCompoundShape*)(this->getWorldEntityCollisionShape()->getCollisionShape());
643
644        return -1;
645    }
646
647    void Pawn::printSpaces(int num)
648    {
649        for(int i=0; i<num; i++)
650            orxout() << " ";
651    }
652}
Note: See TracBrowser for help on using the repository browser.