Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/campaignHS15/src/orxonox/controllers/FightingController.cc @ 10925

Last change on this file since 10925 was 10925, checked in by gania, 8 years ago

synchronized AI with a static tick counter

File size: 14.2 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 *      Gani Aliguzhinov
24 *   Co-authors:
25 *      Fabian 'x3n' Landau, Dominik Solenicki
26 *
27 */
28#include "controllers/FightingController.h"
29#include "core/XMLPort.h"
30#include "util/Math.h"
31
32
33#include "worldentities/pawns/SpaceShip.h"
34
35#include "weaponsystem/WeaponMode.h"
36#include "weaponsystem/WeaponPack.h"
37#include "weaponsystem/Weapon.h"
38#include "weaponsystem/WeaponSlot.h"
39#include "weaponsystem/WeaponSystem.h"
40#include "weaponsystem/Munition.h"
41
42namespace orxonox
43{
44
45    RegisterClass (FightingController);
46   
47    FightingController::FightingController( Context* context ): FlyingController( context )
48    {
49        this->attackRange_ = 2500;
50        this->stopLookingAtTarget();
51        this->bSetupWorked = false;
52        this->timeout_ = 0;
53        RegisterObject( FightingController );
54    }
55    FightingController::~FightingController() 
56    {
57       
58    }
59    void FightingController::XMLPort( Element& xmlelement, XMLPort::Mode mode )
60    {
61        SUPER( FightingController, XMLPort, xmlelement, mode );
62    }
63    void FightingController::lookAtTarget(float dt)
64    {
65        if (!this || !this->getControllableEntity())
66            return;
67        ControllableEntity* entity = this->getControllableEntity();
68        if ( !entity )
69            return;
70        Vector2 coord = get2DViewCoordinates
71            ( entity->getPosition() , 
72            entity->getOrientation()  * WorldEntity::FRONT, 
73            entity->getOrientation()  * WorldEntity::UP, 
74            positionOfTarget_ );
75
76        //rotates should be in range [-1,+1], clamp cuts off all that is not
77        float rotateX = -clamp( coord.x * 10, -1.0f, 1.0f );
78        float rotateY = clamp( coord.y * 10, -1.0f, 1.0f ); 
79   
80        //Yaw and Pitch are enough to start facing the target
81        this->getControllableEntity() ->rotateYaw( ROTATEFACTOR * rotateX * dt );
82        this->getControllableEntity() ->rotatePitch( ROTATEFACTOR * rotateY * dt );
83    }
84    void FightingController::stopLookingAtTarget()
85    {
86        this->bLookAtTarget_ = false;
87    }
88    void FightingController::startLookingAtTarget()
89    {
90        this->bLookAtTarget_ = true;
91    }
92    bool FightingController::hasTarget() const
93    {
94        if ( this->target_ )
95            return true;
96        return false;
97    }
98
99    void FightingController::setTarget( ControllableEntity* target )
100    {
101        this->target_ = target;       
102        if ( this->target_ )
103        {
104            this->setPositionOfTarget( target_->getWorldPosition() );
105        }
106    }
107    void FightingController::setPositionOfTarget( const Vector3& target )
108    {
109        this->positionOfTarget_ = target;
110        this->bHasPositionOfTarget_ = true;
111    }
112    void FightingController::setOrientationOfTarget( const Quaternion& orient )
113    {
114        this->orientationOfTarget_=orient;
115        this->bHasOrientationOfTarget_=true;
116    }
117   
118    void FightingController::maneuver() 
119    {
120        if ( !this->target_ || !this->getControllableEntity())
121            return;
122
123
124        Vector3 thisPosition = this->getControllableEntity()->getWorldPosition();
125        this->setPositionOfTarget(this->target_->getWorldPosition());
126        //this->setOrientationOfTarget(this->target_->getOrientation());
127        Vector3 diffVector = this->positionOfTarget_ - thisPosition;
128        float diffLength = diffVector.length();
129        Vector3 diffUnit = diffVector/diffLength;
130
131        if (!this || !this->getControllableEntity())
132            return;
133
134        //too far? well, come closer then
135        if (diffLength > this->attackRange_)
136        {
137            this->spread_ = 400;
138            this->formationMode_ = FormationMode::DIAMOND;
139            this->bKeepFormation_ = true;
140           
141            this->setTargetPosition(this->positionOfTarget_ - diffUnit * 100.0f);
142        }
143        else
144        {   
145            bool bTargetIsLookingAtThis = CommonController::isLooking (this->target_, this->getControllableEntity(), math::pi/10.0f)
146                || this->deltaHp < 0;
147            this->bKeepFormation_ = false;
148
149            if (!this || !this->getControllableEntity())
150                return;
151            // if (this->actionCounter_ % 3 == 0)
152            if (maneuverCounter_ <= 1.2)
153            {
154                // orxout(internal_error) << "attacking" << endl;
155                this->setTargetPosition(this->positionOfTarget_ - diffUnit * 50.0f);   
156                return;
157            }
158            else if (bTargetIsLookingAtThis || diffLength < 700.0f)
159            {
160                // orxout(internal_error) << "dodging" << endl;
161                if (!this->bStartedDodging_)
162                {
163                    this->bStartedDodging_ = true;
164                    dodge(thisPosition, diffLength, diffUnit);       
165                }
166            }
167            else
168            {
169                if (diffLength < 1000)
170                {
171                // orxout(internal_error) << "looking" << endl;                   
172                    this->stopMoving();
173                    this->startLookingAtTarget();
174
175                }
176                else
177                {
178                // orxout(internal_error) << "closing up" << endl;                   
179                    this->setTargetPosition(this->positionOfTarget_ - diffUnit * 300.0f);
180                }
181            }
182        }
183    }
184   
185    void FightingController::dodge(const Vector3& thisPosition, float diffLength, Vector3& diffUnit)
186    {
187        //d.x*x + d.y*y + d.z*z == 0
188        //z = 1/d.z * (-d.y*y - d.x * x)
189        float x = CommonController::randomInRange (300, 800) * (CommonController::randomInRange(0,1) <= 0.5 ? 1 : -1);
190        float y = CommonController::randomInRange (300, 800) * (CommonController::randomInRange(0,1) <= 0.5 ? 1 : -1);
191        float z = diffUnit.z == 0 ? 0 : (1/diffUnit.z) * (-x * diffUnit.x - y * diffUnit.y);
192        if (diffLength < 150.0f)
193        {
194            this->setTargetPosition(this->positionOfTarget_ + Vector3(z,x,y));
195        }
196        else
197        {
198        this->setTargetPosition(thisPosition + Vector3(x,y,z) + (this->deltaHp < 0 ? -diffUnit * 450.0f : 
199            (diffLength < 700.0f ? -diffUnit*700.0f : diffUnit * 50.0f)));
200
201        }
202        this->boostControl();
203
204    }
205    bool FightingController::canFire() 
206    {
207        //no target? why fire?
208        if (!this->target_ || !this->getControllableEntity())
209            return false;
210        Vector3 newPositionOfTarget = getPredictedPosition(this->getControllableEntity()->getWorldPosition(), 
211                                                           hardcoded_projectile_speed, this->target_->getWorldPosition(), 
212                                                           this->target_->getVelocity());
213        if (!this->target_ || !this->getControllableEntity())
214            return false;
215        //Vector3.isNaN() is what I used on my machine and it worked...
216        if (!(std::isnan(newPositionOfTarget.x) || std::isnan(newPositionOfTarget.y) || std::isnan(newPositionOfTarget.z)))
217        {
218            this->setPositionOfTarget(newPositionOfTarget);
219        }
220
221        return squaredDistanceToTarget() < this->attackRange_*this->attackRange_ && this->isLookingAtTarget(math::pi / 10.0f);
222    }
223
224
225    float FightingController::squaredDistanceToTarget()  const
226    {
227        if (!this || !this->getControllableEntity())
228            return 0;
229        if (!this->target_ || !this->getControllableEntity())
230            return (this->getControllableEntity()->getPosition().squaredDistance(this->targetPosition_));
231        else
232            return (this->getControllableEntity()->getPosition().squaredDistance(this->positionOfTarget_));
233    }
234    bool FightingController::isLookingAtTarget( float angle ) const
235    {
236        if ( !this->getControllableEntity()  || !this->target_ )
237            return false;
238        return CommonController::isLooking(this->getControllableEntity(), this->getTarget(), angle);
239    }
240    void FightingController::setClosestTarget()
241    {
242        this->setTarget (static_cast<ControllableEntity*>( closestTarget() ) ); 
243    }
244   
245    Pawn* FightingController::closestTarget() const
246    {
247        if (!this || !this->getControllableEntity())
248            return 0;
249
250        Pawn* closestTarget = 0;
251        float minDistance =  std::numeric_limits<float>::infinity();
252        Gametype* gt = this->getGametype();
253        for (ObjectList<Pawn>::iterator itP = ObjectList<Pawn>::begin(); itP; ++itP)
254        {
255            if ( CommonController::sameTeam (this->getControllableEntity(), static_cast<ControllableEntity*>(*itP), gt) )
256                continue;
257
258            float distance = CommonController::distance (*itP, this->getControllableEntity());
259            if (distance < minDistance)
260            {
261                closestTarget = *itP;
262                minDistance = distance;
263            }
264        }
265        if (closestTarget)
266        {
267           return closestTarget;
268        } 
269        return 0; 
270    }
271    //I checked it out, rockets DO NOT cause any problems! this->getControllableEntity() is always a SpaceShip
272    void FightingController::doFire()
273    {
274        if (!this->bSetupWorked)
275        {
276            this->setupWeapons();
277        }
278        if (!this->target_ || !this->getControllableEntity())
279        {
280            return;
281        }
282
283        Pawn* pawn = orxonox_cast<Pawn*> (this->getControllableEntity());
284        if (pawn)
285            pawn->setAimPosition (this->positionOfTarget_);
286        // if (pawn->getHealth() < 100)
287        //     orxout(internal_error) << "not full, hp = " << pawn->getHealth() << endl;
288        int firemode;
289        float distance = CommonController::distance (this->getControllableEntity(), this->target_);
290
291        // firemode = distance < 1500 ? (distance > 800 && distance < 1200 ?
292        //                             (this->rocketsLeft_ > 0 && !this->bFiredRocket_ ? getFiremode("RocketFire") : getFiremode ("HsW01"))
293        //                                                      : getFiremode("HsW01")) :
294        //                                                      (distance < 2500 ? getFiremode("LightningGun") : getFiremode("HsW01"));
295        if (distance < 1500)
296        {
297            if (this->rocketsLeft_ > 0 && !this->bFiredRocket_)
298            {
299                firemode = getFiremode ("RocketFire");
300            }
301            else
302            {
303                if (distance > 800)
304                    firemode = getFiremode ("HsW01");
305                else
306                    firemode = getFiremode ("LightningGun");
307            }
308
309        } 
310        // else if (distance < 1000)
311        // {
312        //     if (this->rocketsLeft_ > 0 && !this->bFiredRocket_)
313        //     {
314        //         firemode = getFiremode ("RocketFire");
315        //     }
316        //     else
317        //     {
318        //         firemode = getFiremode ("HsW01");
319        //     }
320        // }
321        else if (distance < 2000)
322        {
323            firemode = getFiremode ("HsW01");
324        }
325        else
326        {
327            firemode = getFiremode ("LightningGun");
328        }
329        if (firemode < 0)
330        {
331            //assuming there is always some weapon with index 0
332            firemode = 0;
333        }
334        if (firemode == getFiremode("RocketFire"))
335        {
336            this->timeout_ = 0.5f;
337            this->rocketsLeft_--;
338            this->bFiredRocket_ = true;
339        }
340        if (firemode == getFiremode("SimpleRocketFire"))
341        {
342            this->rocketsLeft_--;
343        }
344             
345        this->getControllableEntity()->fire(firemode);
346       
347    }
348    void FightingController::setupWeapons() //TODO: Make this function generic!! (at the moment is is based on conventions)
349    {
350        this->bSetupWorked = false;
351        if(this->getControllableEntity())
352        {
353            Pawn* pawn = orxonox_cast<Pawn*>(this->getControllableEntity());
354            if(pawn && pawn->isA(Class(SpaceShip))) //fix for First Person Mode: check for SpaceShip
355            {
356                this->weaponModes_.clear(); // reset previous weapon information
357                WeaponSlot* wSlot = 0;
358                for(int l=0; (wSlot = pawn->getWeaponSlot(l)) ; l++)
359                {
360                    WeaponMode* wMode = 0;
361                    for(int i=0; (wMode = wSlot->getWeapon()->getWeaponmode(i)) ; i++)
362                    {
363                        std::string wName = wMode->getIdentifier()->getName();
364                        // SubclassIdentifier<Munition> munition =  ClassByString(wName);
365                        if (wName == "RocketFire")
366                            this->rocketsLeft_ = 10;
367                            // this->rocketsLeft_ = orxonox_cast<Pawn*>(this->getControllableEntity())->getWeaponSystem()->getMunition(&munition)->getNumMunitionInCurrentMagazine(wMode);
368                        if(this->getFiremode(wName) == -1) //only add a weapon, if it is "new"
369                            weaponModes_[wName] = wMode->getMode();
370                    }
371                }
372                if(weaponModes_.size())//at least one weapon detected
373                    this->bSetupWorked = true;
374            }//pawn->weaponSystem_->getMunition(SubclassIdentifier< Munition > *identifier)->getNumMunition (WeaponMode *user);
375        }
376
377        //orxout (internal_error) << this->rocketsLeft_ << " rockets left" << endl;
378    }
379
380    int FightingController::getFiremode(std::string name)
381    {
382        for (std::map< std::string, int >::iterator it = this->weaponModes_.begin(); it != this->weaponModes_.end(); ++it)
383        {
384            if (it->first == name)
385                return it->second;
386        }
387        return -1;
388    }
389}
Note: See TracBrowser for help on using the repository browser.