Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ai2/src/orxonox/controllers/ArtificialController.cc @ 8757

Last change on this file since 8757 was 8757, checked in by jo, 13 years ago

ai && weapons. Trying to identify each weapon installed on a spaceship.

  • Property svn:eol-style set to native
File size: 43.5 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 *      Dominik Solenicki
26 *
27 */
28
29#include "ArtificialController.h"
30
31#include <vector>
32#include <climits>
33
34#include "util/Math.h"
35#include "util/Convert.h"
36#include "core/CoreIncludes.h"
37#include "core/XMLPort.h"
38#include "core/command/ConsoleCommand.h"
39#include "worldentities/ControllableEntity.h"
40#include "worldentities/pawns/Pawn.h"
41#include "worldentities/pawns/TeamBaseMatchBase.h"
42#include "worldentities/pawns/SpaceShip.h"
43#include "gametypes/TeamDeathmatch.h"
44#include "gametypes/Dynamicmatch.h"
45#include "controllers/WaypointPatrolController.h"
46#include "controllers/NewHumanController.h"
47#include "controllers/DroneController.h"
48#include "weaponsystem/WeaponMode.h"
49#include "weaponsystem/WeaponPack.h"
50#include "weaponsystem/Weapon.h"
51
52
53namespace orxonox
54{
55    SetConsoleCommand("ArtificialController", "formationflight",  &ArtificialController::formationflight);
56    SetConsoleCommand("ArtificialController", "masteraction",     &ArtificialController::masteraction);
57    SetConsoleCommand("ArtificialController", "followme",         &ArtificialController::followme);
58    SetConsoleCommand("ArtificialController", "passivebehaviour", &ArtificialController::passivebehaviour);
59    SetConsoleCommand("ArtificialController", "formationsize",    &ArtificialController::formationsize);
60    SetConsoleCommand("ArtificialController", "setbotlevel",      &ArtificialController::setAllBotLevel);
61
62    static const unsigned int STANDARD_MAX_FORMATION_SIZE = 7;
63    static const int RADIUS_TO_SEARCH_FOR_MASTERS = 5000;
64    static const int FORMATION_LENGTH =  130;
65    static const int FORMATION_WIDTH =  110;
66    static const int FREEDOM_COUNT = 4; //seconds the slaves in a formation will be set free when master attacks an enemy
67    static const float SPEED_MASTER = 0.6f;
68    static const float ROTATEFACTOR_MASTER = 0.2f;
69    static const float SPEED_FREE = 0.8f;
70    static const float ROTATEFACTOR_FREE = 0.8f;
71
72
73    ArtificialController::ArtificialController(BaseObject* creator) : Controller(creator)
74    {
75        RegisterObject(ArtificialController);
76
77        this->target_ = 0;
78        this->formationFlight_ = false;
79        this->passive_ = false;
80        this->maxFormationSize_ = STANDARD_MAX_FORMATION_SIZE;
81        this->myMaster_ = 0;
82        this->freedomCount_ = 0;
83        this->team_ = -1;
84        this->state_ = FREE;
85        this->specificMasterAction_ = NONE;
86        this->specificMasterActionHoldCount_  = 0;
87        this->bShooting_ = false;
88        this->bHasTargetPosition_ = false;
89        this->speedCounter_ = 0.2f;
90        this->targetPosition_ = Vector3::ZERO;
91
92        this->target_.setCallback(createFunctor(&ArtificialController::targetDied, this));
93        this->bSetupWorked = false;
94        this->numberOfWeapons = 0;
95        this->botlevel_ = 0.5f;
96        this->mode_ = DEFAULT;////Vector-implementation: mode_.push_back(DEFAULT);
97        this->timeout_=0;
98    }
99
100    ArtificialController::~ArtificialController()
101    {
102        if (this->isInitialized())
103        {//Vector-implementation: mode_.erase(mode_.begin(),mode_.end());
104            this->removeFromFormation();
105
106            for (ObjectList<ArtificialController>::iterator it = ObjectList<ArtificialController>::begin(); it; ++it)
107            {
108                if (*it != this)
109                {
110                    if (it->myMaster_ == this)
111                    {
112                        COUT(1) << "error: " << this << " is still master in " << (*it) << std::endl;
113                        it->myMaster_ = 0;
114                    }
115
116                    while (true)
117                    {
118                        std::vector<ArtificialController*>::iterator it2 = std::find(it->slaves_.begin(), it->slaves_.end(), this);
119                        if (it2 != it->slaves_.end())
120                        {
121                            COUT(1) << "error: " << this << " is still slave in " << (*it) << std::endl;
122                            it->slaves_.erase(it2);
123                        }
124                        else
125                            break;
126                    }
127                }
128            }
129        }
130    }
131
132    void ArtificialController::XMLPort(Element& xmlelement, XMLPort::Mode mode)
133    {
134        SUPER(ArtificialController, XMLPort, xmlelement, mode);
135
136        XMLPortParam(ArtificialController, "team", setTeam, getTeam, xmlelement, mode).defaultValues(-1);
137        XMLPortParam(ArtificialController, "formationFlight", setFormationFlight, getFormationFlight, xmlelement, mode).defaultValues(false);
138        XMLPortParam(ArtificialController, "formationSize", setFormationSize, getFormationSize, xmlelement, mode).defaultValues(STANDARD_MAX_FORMATION_SIZE);
139        XMLPortParam(ArtificialController, "passive", setPassive, getPassive, xmlelement, mode).defaultValues(false);
140    }
141
142// Documentation only here to get a faster overview for creating a useful documentation...
143
144    /**
145        @brief Activates / deactivates formationflight behaviour
146        @param form activate formflight if form is true
147    */
148    void ArtificialController::formationflight(const bool form)
149    {
150        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
151        {
152            Controller* controller = 0;
153
154            if (it->getController())
155                controller = it->getController();
156            else if (it->getXMLController())
157                controller = it->getXMLController();
158
159            if (!controller)
160                continue;
161
162            ArtificialController *aiController = orxonox_cast<ArtificialController*>(controller);
163
164            if (aiController)
165            {
166                aiController->formationFlight_ = form;
167                if (!form)
168                {
169                    aiController->removeFromFormation();
170                }
171            }
172        }
173    }
174
175    /**
176        @brief Get all masters to do a "specific master action"
177        @param action which action to perform (integer, so it can be called with a console command (tmp solution))
178    */
179    void ArtificialController::masteraction(const int action)
180    {
181        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
182        {
183            Controller* controller = 0;
184
185            if (it->getController())
186                controller = it->getController();
187            else if (it->getXMLController())
188                controller = it->getXMLController();
189
190            if (!controller)
191                continue;
192
193            ArtificialController *aiController = orxonox_cast<ArtificialController*>(controller);
194
195            if(aiController && aiController->state_ == MASTER)
196            {
197                if (action == 1)
198                    aiController->spinInit();
199                if (action == 2)
200                    aiController->turn180Init();
201            }
202        }
203    }
204
205    /**
206        @brief A human player gets followed by its nearest master. Initiated by console command, so far intended for demonstration puproses (possible future pickup).
207    */
208    void ArtificialController::followme()
209    {
210
211        Pawn *humanPawn = NULL;
212        NewHumanController *currentHumanController = NULL;
213        std::vector<ArtificialController*> allMasters;
214
215        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
216        {
217            Controller* controller = 0;
218
219            if (it->getController())
220                controller = it->getController();
221            else if (it->getXMLController())
222                controller = it->getXMLController();
223
224            if (!controller)
225                continue;
226
227            currentHumanController = orxonox_cast<NewHumanController*>(controller);
228
229            if(currentHumanController) humanPawn = *it;
230
231            ArtificialController *aiController = orxonox_cast<ArtificialController*>(controller);
232
233            if(aiController && aiController->state_ == MASTER)
234                allMasters.push_back(aiController);
235
236        }
237
238        if((humanPawn != NULL) && (allMasters.size() != 0))
239        {
240                float posHuman = humanPawn->getPosition().length();
241                float distance = 0.0f;
242                float minDistance = FLT_MAX;
243                int index = 0;
244                int i = 0;
245
246                for(std::vector<ArtificialController*>::iterator it = allMasters.begin(); it != allMasters.end(); it++, i++)
247                    {
248                        if (!ArtificialController::sameTeam((*it)->getControllableEntity(), humanPawn, (*it)->getGametype())) continue;
249                        distance = posHuman - (*it)->getControllableEntity()->getPosition().length();
250                        if(distance < minDistance) index = i;
251                    }
252                allMasters[index]->followInit(humanPawn);
253            }
254
255    }
256
257    /**
258        @brief Sets shooting behaviour of pawns.
259        @param passive if true, bots won't shoot.
260    */
261    void ArtificialController::passivebehaviour(const bool passive)
262    {
263        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
264        {
265            Controller* controller = 0;
266
267            if (it->getController())
268                controller = it->getController();
269            else if (it->getXMLController())
270                controller = it->getXMLController();
271
272            if (!controller)
273                continue;
274
275            ArtificialController *aiController = orxonox_cast<ArtificialController*>(controller);
276
277            if(aiController)
278            {
279                aiController->passive_ = passive;
280            }
281        }
282    }
283
284
285    /**
286        @brief Sets maximal formation size
287        @param size maximal formation size.
288    */
289    void ArtificialController::formationsize(const int size)
290    {
291        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
292        {
293            Controller* controller = 0;
294
295            if (it->getController())
296                controller = it->getController();
297            else if (it->getXMLController())
298                controller = it->getXMLController();
299
300            if (!controller)
301                continue;
302
303            ArtificialController *aiController = orxonox_cast<ArtificialController*>(controller);
304
305            if(aiController)
306            {
307                aiController->maxFormationSize_ = size;
308            }
309        }
310    }
311
312    /**
313        @brief Gets called when ControllableEntity is being changed. Resets the bot when it dies.
314    */
315    void ArtificialController::changedControllableEntity()
316    {
317        if (!this->getControllableEntity())
318            this->removeFromFormation();
319    }
320
321    void ArtificialController::removeFromFormation()
322    {
323        if (this->state_ == SLAVE || this->myMaster_) // slaves can also be temporary free, so check if myMaster_ is set
324            this->unregisterSlave();
325        else if (this->state_ == MASTER)
326            this->setNewMasterWithinFormation();
327    }
328
329    void ArtificialController::moveToPosition(const Vector3& target)
330    {
331        if (!this->getControllableEntity())
332            return;
333
334        // Slave uses special movement if its master is in FOLLOW mode
335        if(this->state_ == SLAVE && this->myMaster_ && this->myMaster_->specificMasterAction_ == FOLLOW)
336        {
337//             this->followForSlaves(target);
338//             return;
339        }
340
341        Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, target);
342        float distance = (target - this->getControllableEntity()->getPosition()).length();
343
344
345        if(this->state_ == FREE)
346        {
347            if (this->target_ || distance > 10)
348            {
349                // Multiply with ROTATEFACTOR_FREE to make them a bit slower
350                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_FREE * sgn(coord.x) * coord.x*coord.x);
351                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_FREE * sgn(coord.y) * coord.y*coord.y);
352            }
353
354            if (this->target_ && distance < 200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
355            {
356              this->getControllableEntity()->moveFrontBack(-0.05f); // They don't brake with full power to give the player a chance
357            } else this->getControllableEntity()->moveFrontBack(SPEED_FREE);
358        }
359
360
361
362        if(this->state_ == MASTER)
363        {
364            if (this->target_ || distance > 10)
365            {
366                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_MASTER * sgn(coord.x) * coord.x*coord.x);
367                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_MASTER * sgn(coord.y) * coord.y*coord.y);
368            }
369
370            if (this->target_ && distance < 200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
371            {
372                this->getControllableEntity()->moveFrontBack(-0.05f);
373            } else this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
374        }
375
376
377
378        if(this->state_ == SLAVE)
379        {
380
381           this->getControllableEntity()->rotateYaw(-2.0f * ROTATEFACTOR_MASTER * sgn(coord.x) * coord.x*coord.x);
382           this->getControllableEntity()->rotatePitch(2.0f * ROTATEFACTOR_MASTER * sgn(coord.y) * coord.y*coord.y);
383
384            if (distance < 300)
385            {
386                if (distance < 40)
387                {
388                    this->getControllableEntity()->moveFrontBack(0.8f*SPEED_MASTER);
389                } else this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER);
390
391            } else {
392                this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER + distance/300.0f);
393            }
394        }
395
396        if (distance < 10)
397        {
398            this->positionReached();
399        }
400    }
401
402    void ArtificialController::moveToTargetPosition()
403    {
404        this->moveToPosition(this->targetPosition_);
405    }
406
407    /**
408        @brief Unregisters a slave from its master. Initiated by a slave.
409    */
410    void ArtificialController::unregisterSlave()
411    {
412        if (this->myMaster_)
413        {
414            std::vector<ArtificialController*>::iterator it = std::find(this->myMaster_->slaves_.begin(), this->myMaster_->slaves_.end(), this);
415            if (it != this->myMaster_->slaves_.end())
416                this->myMaster_->slaves_.erase(it);
417        }
418
419        this->myMaster_ = 0;
420        this->state_ = FREE;
421    }
422
423    void ArtificialController::searchNewMaster()
424    {
425
426        if (!this->getControllableEntity())
427            return;
428
429        this->targetPosition_ = this->getControllableEntity()->getPosition();
430        this->forgetTarget();
431        int teamSize = 0;
432        //go through all pawns
433        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
434        {
435            //same team?
436            if (!ArtificialController::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it), this->getGametype()))
437                continue;
438
439            //has it an ArtificialController?
440            Controller* controller = 0;
441
442            if (it->getController())
443                controller = it->getController();
444            else if (it->getXMLController())
445                controller = it->getXMLController();
446
447            if (!controller)
448                continue;
449
450            //is pawn oneself?
451            if (orxonox_cast<ControllableEntity*>(*it) == this->getControllableEntity())
452                continue;
453
454            teamSize++;
455
456            ArtificialController *newMaster = orxonox_cast<ArtificialController*>(controller);
457
458            //is it a master?
459            if (!newMaster || newMaster->state_ != MASTER)
460                continue;
461
462            float distance = (it->getPosition() - this->getControllableEntity()->getPosition()).length();
463
464            // is pawn in range?
465            if (distance < RADIUS_TO_SEARCH_FOR_MASTERS)
466            {
467                if(newMaster->slaves_.size() > this->maxFormationSize_) continue;
468
469                for(std::vector<ArtificialController*>::iterator itSlave = this->slaves_.begin(); itSlave != this->slaves_.end(); itSlave++)
470                {
471                    (*itSlave)->myMaster_ = newMaster;
472                    newMaster->slaves_.push_back(*itSlave);
473                }
474                this->slaves_.clear();
475                this->state_ = SLAVE;
476
477                this->myMaster_ = newMaster;
478                newMaster->slaves_.push_back(this);
479
480                break;
481            }
482        }
483
484        if (this->state_ != SLAVE  && teamSize != 0)
485        {
486            this->state_ = MASTER;
487            this->myMaster_ = 0;
488        }
489    }
490
491    /**
492        @brief Commands the slaves of a master into a formation. Sufficiently fast not to be called within tick. Initiated by a master.
493    */
494    void ArtificialController::commandSlaves()
495    {
496        if(this->state_ != MASTER) return;
497
498        Quaternion orient = this->getControllableEntity()->getOrientation();
499        Vector3 dest = this->getControllableEntity()->getPosition();
500
501        // 1 slave: follow
502        if (this->slaves_.size() == 1)
503        {
504            dest += 4*orient*WorldEntity::BACK;
505            this->slaves_.front()->setTargetPosition(dest);
506        }
507        else
508        {
509            dest += 1.0f*orient*WorldEntity::BACK;
510            Vector3 pos = Vector3::ZERO;
511            int i = 1;
512
513            for(std::vector<ArtificialController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
514            {
515                pos = Vector3::ZERO;
516                if (i <= 1) pos += dest  + (float)FORMATION_WIDTH*(orient*WorldEntity::LEFT);
517                if (i == 2) pos += dest  + (float)FORMATION_WIDTH*(orient*WorldEntity::RIGHT);
518                if (i == 3) pos += dest  + (float)FORMATION_WIDTH*(orient*WorldEntity::UP);
519                if (i >= 4)
520                {
521                    pos += dest  + (float)FORMATION_WIDTH*(orient*WorldEntity::DOWN);
522                    i = 1;
523                    dest += (float)FORMATION_LENGTH*(orient*WorldEntity::BACK);
524                    (*it)->setTargetPosition(pos);
525                    continue;
526                }
527                i++;
528                (*it)->setTargetPosition(pos);
529            }
530        }
531    }
532
533    /**
534        @brief Sets a new master within the formation. Called by a master.
535    */
536    void ArtificialController::setNewMasterWithinFormation()
537    {
538        if(this->state_ != MASTER) return;
539
540        if (!this->slaves_.empty())
541        {
542            ArtificialController *newMaster = this->slaves_.back();
543            this->slaves_.pop_back();
544
545            newMaster->state_ = MASTER;
546            newMaster->slaves_ = this->slaves_;
547            newMaster->myMaster_ = 0;
548
549            for(std::vector<ArtificialController*>::iterator it = newMaster->slaves_.begin(); it != newMaster->slaves_.end(); it++)
550            {
551                (*it)->myMaster_ = newMaster;
552            }
553        }
554
555        this->slaves_.clear();
556        this->specificMasterAction_ = NONE;
557        this->state_ = FREE;
558    }
559
560    /**
561        @brief Frees all slaves form a master. Initiated by a master.
562    */
563    void ArtificialController::freeSlaves()
564    {
565        if(this->state_ != MASTER) return;
566
567        for(std::vector<ArtificialController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
568        {
569            (*it)->state_ = FREE;
570            (*it)->myMaster_ = 0;
571        }
572        this->slaves_.clear();
573    }
574
575    /**
576        @brief Master sets its slaves free for @ref FREEDOM_COUNT seconds.
577    */
578    void ArtificialController::forceFreeSlaves()
579    {
580        if(this->state_ != MASTER) return;
581
582        for(std::vector<ArtificialController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
583        {
584            (*it)->state_ = FREE;
585            (*it)->forceFreedom();
586            (*it)->targetPosition_ = this->targetPosition_;
587            (*it)->bShooting_ = true;
588//             (*it)->getControllableEntity()->fire(0);// fire once for fun
589        }
590    }
591
592    void ArtificialController::loseMasterState()
593    {
594        this->freeSlaves();
595        this->state_ = FREE;
596    }
597
598
599    void ArtificialController::forceFreedom()
600    {
601        this->freedomCount_ = FREEDOM_COUNT;
602    }
603
604    /**
605        @brief Checks wether caller has been forced free, decrements time to stay forced free.
606        @return true if forced free.
607    */
608    bool ArtificialController::forcedFree()
609    {
610        if(this->freedomCount_ > 0)
611        {
612            this->freedomCount_--;
613            return true;
614        } else return false;
615    }
616
617    /**
618        @brief Used to continue a "specific master action" for a certain time and resuming normal behaviour after.
619    */
620    void ArtificialController::specificMasterActionHold()
621    {
622        if(this->state_ != MASTER) return;
623
624        if (specificMasterActionHoldCount_ == 0)
625         {
626            this->specificMasterAction_ = NONE;
627            this->searchNewTarget();
628         }
629        else specificMasterActionHoldCount_--;
630    }
631
632    /**
633        @brief Master initializes a 180 degree turn. Leads to a "specific master action".
634    */
635    void ArtificialController::turn180Init()
636    {
637        if(this->state_ != MASTER) return;
638
639        Quaternion orient = this->getControllableEntity()->getOrientation();
640
641        this->setTargetPosition(this->getControllableEntity()->getPosition() + 1000.0f*orient*WorldEntity::BACK);
642
643        this->specificMasterActionHoldCount_ = 4;
644
645        this->specificMasterAction_ = TURN180;
646    }
647
648    /**
649        @brief Execute the 180 degree turn. Called within tick.
650    */
651    void ArtificialController::turn180()
652    {
653            Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, this->targetPosition_);
654
655            this->getControllableEntity()->rotateYaw(-2.0f * sgn(coord.x) * coord.x*coord.x);
656            this->getControllableEntity()->rotatePitch(2.0f * sgn(coord.y) * coord.y*coord.y);
657
658            this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
659    }
660
661    /**
662        @brief Master initializes a spin around its looking direction axis. Leads to a "specific master action".
663    */
664    void ArtificialController::spinInit()
665    {
666        if(this->state_ != MASTER) return;
667        this->specificMasterAction_ = SPIN;
668        this->specificMasterActionHoldCount_ = 10;
669    }
670
671    /**
672        @brief Execute the spin. Called within tick.
673    */
674    void ArtificialController::spin()
675    {
676            this->moveToTargetPosition();
677            this->getControllableEntity()->rotateRoll(0.8f);
678    }
679
680    /**
681        @brief Master begins to follow a pawn. Is a "specific master action".
682        @param pawn pawn to follow.
683        @param always follows pawn forever if true (false if omitted).
684        @param secondsToFollow seconds to follow the pawn if always is false. Will follow pawn 100 seconds if omitted (set in header).
685    */
686    void ArtificialController::followInit(Pawn* pawn, const bool always, const int secondsToFollow)
687    {
688        if (pawn == NULL || this->state_ != MASTER)
689            return;
690        this->specificMasterAction_  =  FOLLOW;
691
692        this->setTarget(pawn);
693        if (!always)
694            this->specificMasterActionHoldCount_ = secondsToFollow;
695        else
696            this->specificMasterActionHoldCount_ = INT_MAX; //for now...
697
698    }
699
700
701    /**
702        @brief Master begins to follow a randomly chosen human player of the same team. Is a "specific master action".
703    */
704    void ArtificialController::followRandomHumanInit()
705    {
706
707        Pawn *humanPawn = NULL;
708        NewHumanController *currentHumanController = NULL;
709
710        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
711        {
712            if (!it->getController())
713                continue;
714
715            currentHumanController = orxonox_cast<NewHumanController*>(it->getController());
716            if(currentHumanController)
717            {
718                if (!ArtificialController::sameTeam(this->getControllableEntity(), *it, this->getGametype())) continue;
719                humanPawn = *it;
720                break;
721            }
722        }
723
724        if((humanPawn != NULL))
725                this->followInit(humanPawn);
726    }
727
728    /**
729        @brief Master follows target with adjusted speed. Called within tick.
730    */
731    void ArtificialController::follow()
732    {
733        if (this->target_)
734            this->moveToPosition(this->target_->getPosition());
735        else
736            this->specificMasterActionHoldCount_ = 0;
737/*
738        if (!this->getControllableEntity())
739            return;
740
741        float distance = (this->target_->getPosition() - this->getControllableEntity()->getPosition()).length();
742
743        Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, this->target_->getPosition());
744
745
746        this->getControllableEntity()->rotateYaw(-0.8f * sgn(coord.x) * coord.x*coord.x);
747        this->getControllableEntity()->rotatePitch(0.8f * sgn(coord.y) * coord.y*coord.y);
748
749        float speedDiv = this->getControllableEntity()->getVelocity().squaredLength() - this->target_->getVelocity().squaredLength();
750
751COUT(0) << "~follow distance: " << distance << "SpeedCounter: " << this->speedCounter_ << "~speedDiv: " << speedDiv << std::endl;
752        if (distance < 800)
753        {
754            if (distance < 200)
755            {
756                this->speedCounter_ -= 0.5f;
757                if(this->speedCounter_ < 0) this->speedCounter_ = 0.0f;
758                this->getControllableEntity()->moveFrontBack(speedCounter_);
759            } else {
760                if(speedDiv < 0)
761                    this->speedCounter_ +=  0.01f;
762                else
763                    this->speedCounter_ -= 0.05f;
764                this->getControllableEntity()->moveFrontBack(speedCounter_);
765            }
766
767        } else {
768            this->speedCounter_ += 0.05f;
769            this->getControllableEntity()->moveFrontBack(speedCounter_ + distance/300.0f);
770        }
771//         if (this->getControllableEntity()->getVelocity().squaredLength() > 50.0f) this->speedCounter_ = 0;
772
773*/
774    }
775
776
777    /**
778        @brief Slave moving behaviour when master is following a pawn, gets redirected from moveToPosition(const Vector3& target)). Called within tick.
779    */
780    void ArtificialController::followForSlaves(const Vector3& target)
781    {
782
783/*
784        if (!this->getControllableEntity() && !this->myMaster_ && this->myMaster_->state_ != FOLLOW && !this->myMaster_->target_)
785            return;
786
787        float distance = (target - this->getControllableEntity()->getPosition()).length();
788
789        Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, target);
790
791
792        this->getControllableEntity()->rotateYaw(-0.8f * sgn(coord.x) * coord.x*coord.x);
793        this->getControllableEntity()->rotatePitch(0.8f * sgn(coord.y) * coord.y*coord.y);
794
795
796        float speedDiv = this->getControllableEntity()->getVelocity().squaredLength() - this->myMaster_->target_->getVelocity().squaredLength();
797
798
799         if (distance < 800)
800        {
801            if (distance < 200)
802            {
803                this->speedCounter_ -= 5.0f;
804                if(this->speedCounter_ < 0) this->speedCounter_ = 0.0f;
805                this->getControllableEntity()->moveFrontBack(speedCounter_);
806            } else {
807                if(speedDiv < 0)
808                    this->speedCounter_ +=  0.01f;
809                else
810                    this->speedCounter_ -= 0.05f;
811                this->getControllableEntity()->moveFrontBack(speedCounter_);
812            }
813
814        } else {
815            this->speedCounter_ += 0.05f;
816            this->getControllableEntity()->moveFrontBack(speedCounter_ + distance/300.0f);
817        }
818//         if (this->getControllableEntity()->getVelocity().squaredLength() > 50.0f) this->speedCounter_ = 0;
819*/
820    }
821
822
823    void ArtificialController::setTargetPosition(const Vector3& target)
824    {
825        this->targetPosition_ = target;
826        this->bHasTargetPosition_ = true;
827    }
828
829    void ArtificialController::searchRandomTargetPosition()
830    {
831        this->targetPosition_ = Vector3(rnd(-2000,2000), rnd(-2000,2000), rnd(-2000,2000));
832        this->bHasTargetPosition_ = true;
833    }
834
835    void ArtificialController::setTarget(Pawn* target)
836    {
837        this->target_ = target;
838
839        if (target)
840            this->targetPosition_ = target->getPosition();
841    }
842
843    void ArtificialController::searchNewTarget()
844    {
845        if (!this->getControllableEntity())
846            return;
847
848        this->targetPosition_ = this->getControllableEntity()->getPosition();
849        this->forgetTarget();
850
851        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
852        {
853            if (ArtificialController::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it), this->getGametype()))
854                continue;
855
856            /* So AI won't choose invisible Spaceships as target */
857            if (!it->getRadarVisibility())
858                continue;
859
860            if (static_cast<ControllableEntity*>(*it) != this->getControllableEntity())
861            {
862                float speed = this->getControllableEntity()->getVelocity().length();
863                Vector3 distanceCurrent = this->targetPosition_ - this->getControllableEntity()->getPosition();
864                Vector3 distanceNew = it->getPosition() - this->getControllableEntity()->getPosition();
865                if (!this->target_ || it->getPosition().squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceNew) / speed / distanceNew.length()) / math::twoPi)
866                        < this->targetPosition_.squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceCurrent) / speed / distanceCurrent.length()) / math::twoPi) + rnd(-250, 250))
867                {
868                    this->target_ = (*it);
869                    this->targetPosition_ = it->getPosition();
870                }
871            }
872        }
873    }
874
875    void ArtificialController::forgetTarget()
876    {
877        this->target_ = 0;
878        this->bShooting_ = false;
879    }
880
881    void ArtificialController::aimAtTarget()
882    {
883        if (!this->target_ || !this->getControllableEntity())
884            return;
885
886        static const float hardcoded_projectile_speed = 1250;
887
888        this->targetPosition_ = getPredictedPosition(this->getControllableEntity()->getPosition(), hardcoded_projectile_speed, this->target_->getPosition(), this->target_->getVelocity());
889        this->bHasTargetPosition_ = (this->targetPosition_ != Vector3::ZERO);
890
891        Pawn* pawn = orxonox_cast<Pawn*>(this->getControllableEntity());
892        if (pawn)
893            pawn->setAimPosition(this->targetPosition_);
894    }
895
896    bool ArtificialController::isCloseAtTarget(float distance) const
897    {
898        if (!this->getControllableEntity())
899            return false;
900
901        if (!this->target_)
902            return (this->getControllableEntity()->getPosition().squaredDistance(this->targetPosition_) < distance*distance);
903        else
904            return (this->getControllableEntity()->getPosition().squaredDistance(this->target_->getPosition()) < distance*distance);
905    }
906
907    bool ArtificialController::isLookingAtTarget(float angle) const
908    {
909        if (!this->getControllableEntity())
910            return false;
911
912        return (getAngle(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->targetPosition_) < angle);
913    }
914
915    void ArtificialController::abandonTarget(Pawn* target)
916    {
917        if (target == this->target_)
918            this->targetDied();
919    }
920
921    void ArtificialController::targetDied()
922    {
923        this->forgetTarget();
924        this->searchRandomTargetPosition();
925    }
926
927    bool ArtificialController::sameTeam(ControllableEntity* entity1, ControllableEntity* entity2, Gametype* gametype)
928    {
929        if (entity1 == entity2)
930            return true;
931
932        int team1 = -1;
933        int team2 = -1;
934
935        Controller* controller = 0;
936        if (entity1->getController())
937            controller = entity1->getController();
938        else
939            controller = entity1->getXMLController();
940        if (controller)
941        {
942            ArtificialController* ac = orxonox_cast<ArtificialController*>(controller);
943            if (ac)
944                team1 = ac->getTeam();
945        }
946
947        if (entity2->getController())
948            controller = entity2->getController();
949        else
950            controller = entity2->getXMLController();
951        if (controller)
952        {
953            ArtificialController* ac = orxonox_cast<ArtificialController*>(controller);
954            if (ac)
955                team2 = ac->getTeam();
956        }
957
958        TeamDeathmatch* tdm = orxonox_cast<TeamDeathmatch*>(gametype);
959        if (tdm)
960        {
961            if (entity1->getPlayer())
962                team1 = tdm->getTeam(entity1->getPlayer());
963
964            if (entity2->getPlayer())
965                team2 = tdm->getTeam(entity2->getPlayer());
966        }
967
968        TeamBaseMatchBase* base = 0;
969        base = orxonox_cast<TeamBaseMatchBase*>(entity1);
970        if (base)
971        {
972            switch (base->getState())
973            {
974                case BaseState::ControlTeam1:
975                    team1 = 0;
976                    break;
977                case BaseState::ControlTeam2:
978                    team1 = 1;
979                    break;
980                case BaseState::Uncontrolled:
981                default:
982                    team1 = -1;
983            }
984        }
985        base = orxonox_cast<TeamBaseMatchBase*>(entity2);
986        if (base)
987        {
988            switch (base->getState())
989            {
990                case BaseState::ControlTeam1:
991                    team2 = 0;
992                    break;
993                case BaseState::ControlTeam2:
994                    team2 = 1;
995                    break;
996                case BaseState::Uncontrolled:
997                default:
998                    team2 = -1;
999            }
1000        }
1001
1002        DroneController* droneController = 0;
1003        droneController = orxonox_cast<DroneController*>(entity1->getController());
1004        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity2)
1005            return true;
1006        droneController = orxonox_cast<DroneController*>(entity2->getController());
1007        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity1)
1008            return true;
1009        DroneController* droneController1 = orxonox_cast<DroneController*>(entity1->getController());
1010        DroneController* droneController2 = orxonox_cast<DroneController*>(entity2->getController());
1011        if (droneController1 && droneController2 && droneController1->getOwner() == droneController2->getOwner())
1012            return true;
1013
1014        Dynamicmatch* dynamic = orxonox_cast<Dynamicmatch*>(gametype);
1015        if (dynamic)
1016        {
1017            if (dynamic->notEnoughPigs||dynamic->notEnoughKillers||dynamic->notEnoughChasers) {return false;}
1018
1019            if (entity1->getPlayer())
1020                team1 = dynamic->getParty(entity1->getPlayer());
1021
1022            if (entity2->getPlayer())
1023                team2 = dynamic->getParty(entity2->getPlayer());
1024
1025            if (team1 ==-1 ||team2 ==-1 ) {return false;}
1026            else if (team1 == dynamic->chaser && team2 != dynamic->chaser) {return false;}
1027            else if (team1 == dynamic->piggy && team2 == dynamic->chaser) {return false;}
1028            else if (team1 == dynamic->killer && team2 == dynamic->chaser) {return false;}
1029            else return true;
1030        }
1031
1032        return (team1 == team2 && team1 != -1);
1033    }
1034
1035    /**
1036        @brief DoFire is called when a bot should shoot and decides which weapon is used and whether the bot shoots at all.
1037    */
1038    void ArtificialController::doFire()
1039    {
1040        if(!bSetupWorked)//setup: find out which weapons are active ! hard coded: laser is "0", lens flare is "1", ...
1041        {
1042            this->setupWeapons();
1043            if(numberOfWeapons > 0)
1044                bSetupWorked = true;
1045        }
1046        else if(this->getControllableEntity() && (numberOfWeapons>0)&&this->bShooting_ && this->isCloseAtTarget((1 + 2*botlevel_)*1000) && this->isLookingAtTarget(math::pi / 20.0f))
1047        {
1048            float random = rnd(1);//
1049            if (this->isCloseAtTarget(130) && weapons[1] )
1050            {//LENSFLARE: short range weapon
1051                this->getControllableEntity()->fire(1); //ai uses lens flare if they're close enough to the target
1052            }
1053            else if(weapons[3] && this->isCloseAtTarget(400) && (projectiles[3] > 0) && (random < this->botlevel_) )
1054            {//ROCKET: mid range weapon
1055                this->mode_ = ROCKET; //Vector-implementation: mode_.push_back(ROCKET);
1056                this->getControllableEntity()->fire(3); //launch rocket
1057                if(this->getControllableEntity() && this->target_) //after fire(3) is called, getControllableEntity() refers to the rocket!
1058                {
1059                    float speed = this->getControllableEntity()->getVelocity().length() - target_->getVelocity().length();
1060                    if(!speed) speed = 0.1f;
1061                    float distance = target_->getPosition().length() - this->getControllableEntity()->getPosition().length();
1062                    this->timeout_= distance/speed*sgn(speed*distance) + 1.8f; //predicted time of target hit (+ tolerance)
1063                }
1064                else
1065                    this->timeout_ = 4.0f; //TODO: find better default value
1066                this->projectiles[3] -= 1; //decrease ammo
1067            }
1068            else if (weapons[0])//LASER: default weapon
1069                this->getControllableEntity()->fire(0);
1070        }
1071    }
1072
1073    /**
1074        @brief Information gathering: Which weapons are ready to use?
1075    */
1076    void ArtificialController::setupWeapons() //TODO: Make this function generic!! (at the moment is is based on conventions)
1077    {
1078        if(this->getControllableEntity())
1079        {
1080            Pawn* pawn = orxonox_cast<Pawn*>(this->getControllableEntity());
1081            if(pawn)
1082            {
1083                this->analyseWeapons(pawn);
1084                for(unsigned int i=0; i < WeaponSystem::MAX_WEAPON_MODES; i++)
1085                {
1086                    //const std::string wpn = getWeaponname(i, 0, pawn); COUT(0)<<wpn<< std::endl;//Temporary debug info.
1087                    /*if(wpn=="") //future, more generic implementation; until now, only LaserMunition works. Is this a bug??
1088                        weapons[i]=false;
1089                    else if(wpn=="LaserMunition")//other munitiontypes are not defined yet :-(
1090                        weapons[0]=true;
1091                    else if(wpn=="FusionMunition")
1092                        weapons[1]=true;
1093                    else if(wpn=="TargetSeeking Rockets")
1094                        weapons[2]=true;
1095                    else if(wpn=="RocketMunition")
1096                        weapons[3]=true;
1097                    else
1098                        COUT(1)<< wpn << + << " has to be added in ArtificialController.cc as new weapon." << std::endl;
1099                    */
1100                    if(pawn->getWeaponSet(i)) //main part: find which weapons a pawn can use; hard coded at the moment!
1101                    {
1102                        weapons[i] = true;
1103                        projectiles[i] = 10; //TODO: how to get data?? getWeaponmode(i)->getMunition()->getNumMunition(WeaponMode* user)
1104                          numberOfWeapons++;
1105                    }
1106                    else
1107                        weapons[i] = false;
1108                }
1109                 //pawn->weaponSystem_->getMunition(SubclassIdentifier< Munition > *identifier)->getNumMunition (WeaponMode *user);
1110            }
1111        }
1112    }
1113
1114    const std::string ArtificialController::getWeaponname(int i, int u, Pawn* pawn)//Search through all wPacks,
1115    {//is there a way to minimize this long if-return structure, without triggering nullpointer exceptions?
1116        if(!pawn) return "a";
1117        WeaponPack* wPack = pawn->getWeaponPack(u);
1118        if(!wPack) return "b";
1119        Weapon* wpn = wPack->getWeapon(i);
1120        if(!wpn && u<10 && i>0)
1121        {
1122            return this->getWeaponname(i, u+1, pawn);
1123        }
1124        else if(!wpn)
1125            return "c";
1126        //return wpn->getName();
1127        WeaponMode* wMode = wpn->getWeaponmode(0);
1128        if(!wMode) return "d";
1129        return wMode->getMunitionName();//getName();
1130    }//pawn->getWeaponpack(i)->getWeapon(i)->getWeaponmode(i)->getMunitionName()
1131    /**
1132        @brief Display how a spaceship is equiped with weapons. TODO: why are only 3 out of 8 weapons displayed??
1133    */
1134    void ArtificialController::analyseWeapons(Pawn* pawn)
1135    {
1136        int max=10, i=0, j=0, k=0;
1137        if(!pawn) {COUT(0)<<"NO PAWN"<<std::endl; return;}
1138        while(i<max)
1139        {
1140            WeaponPack* wPack = pawn->getWeaponPack(i); //WeaponSet* wSet = pawn->getWeaponSet(i);
1141            i++;
1142            if(wPack==NULL) continue;
1143            while(j<max)
1144            {
1145                Weapon* wpn = wPack->getWeapon(j);
1146                j++;
1147                if(wpn==NULL) continue;
1148                while(k<max)
1149                {
1150                    WeaponMode* wMode = wpn->getWeaponmode(k);
1151                    k++;
1152                    if(wMode==NULL) continue;
1153                    COUT(0)<<wMode->getName()<<": weaponpack "+multi_cast<std::string>(i-1)<<", weapon "<<multi_cast<std::string>(j-1)<<", weaponmode "<<multi_cast<std::string>(k-1)<<std::endl;
1154                }
1155            }
1156        }
1157    }
1158
1159
1160    void ArtificialController::setBotLevel(float level)
1161    {
1162        if (level < 0.0f)
1163            this->botlevel_ = 0.0f;
1164        else if (level > 1.0f)
1165            this->botlevel_ = 1.0f;
1166        else
1167            this->botlevel_ = level;
1168    }
1169
1170    void ArtificialController::setAllBotLevel(float level)
1171    {
1172        for (ObjectList<ArtificialController>::iterator it = ObjectList<ArtificialController>::begin(); it != ObjectList<ArtificialController>::end(); ++it)
1173            it->setBotLevel(level);
1174    }
1175
1176    void ArtificialController::setPreviousMode()
1177    {
1178        this->mode_ = DEFAULT; //Vector-implementation: mode_.pop_back();
1179    }
1180
1181    void ArtificialController::boostControl()
1182    {
1183        SpaceShip* ship = orxonox_cast<SpaceShip*>(this->getControllableEntity());
1184        if(ship == NULL) return;
1185        if(ship->getBoostPower()*1.5f > ship->getInitialBoostPower() )//upper limit ->boost
1186            this->getControllableEntity()->boost(true);
1187        else if(ship->getBoostPower()*4.0f < ship->getInitialBoostPower())//lower limit ->do not boost
1188            this->getControllableEntity()->boost(false);
1189    }
1190
1191}
Note: See TracBrowser for help on using the repository browser.