Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/orxonox/controllers/FormationController.cc @ 11071

Last change on this file since 11071 was 11071, checked in by landauf, 8 years ago

merged branch cpp11_v3 back to trunk

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