Advanced Strategic Command
ai.h
Go to the documentation of this file.
1 
5 /*
6  This file is part of Advanced Strategic Command; http://www.asc-hq.de
7  Copyright (C) 1994-2010 Martin Bickel and Marc Schellenberger
8 
9  This program is free software; you can redistribute it and/or modify
10  it under the terms of the GNU General Public License as published by
11  the Free Software Foundation; either version 2 of the License, or
12  (at your option) any later version.
13 
14  This program is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  GNU General Public License for more details.
18 
19  You should have received a copy of the GNU General Public License
20  along with this program; see the file COPYING. If not, write to the
21  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
22  Boston, MA 02111-1307 USA
23 */
24 
25 #ifndef aiH_included
26 #define aiH_included
27 
28 
29 #include <utility>
30 #include <map>
31 #include <vector>
32 #include <list>
33 
34 #include "../typen.h"
35 #include "../terraintype.h"
36 #include "../objecttype.h"
37 #include "../spfst.h"
38 #include "../buildingtype.h"
39 #include "../astar2.h"
40 #include "../actions/context.h"
41 #include "../attack.h"
42 
43 
44  class AI : public BaseAI {
45  bool benchMark;
46  bool strictChecks;
47 
48  //bool _isRunning;
49  //VisibilityStates _vision;
50  int unitCounter;
51  int player;
52 
53  int maxTrooperMove;
54  int maxTransportMove;
55  int maxUnitMove;
56  int maxWeapDist[8];
57  int baseThreatsCalculated;
58 
59  GameMap* activemap;
60  MapDisplayInterface* mapDisplay;
61 
62  class ServiceOrder {
63  AI* ai;
64  int targetUnitID;
65  int serviceUnitID;
66 
68  GameTime time;
69  int failure;
70  Building* nextServiceBuilding;
71  int nextServiceBuildingDistance;
72  bool active;
73  public:
74 
75  enum Service { srv_repair, srv_resource, srv_ammo };
76 
77  Service requiredService;
78  int position;
79 
80  int getServiceID() const;
81 
82  ServiceOrder ( ) : ai ( NULL ), targetUnitID ( 0 ), serviceUnitID ( 0 ), failure ( 0 ), nextServiceBuilding ( 0 ), active ( false ) {};
83  ServiceOrder ( AI* _ai, Service _requiredService, int UnitID, int _pos = -1 );
84  ServiceOrder ( AI* _ai, tnstream& stream );
85  AStar3D::Path::iterator lastmatchServiceOrder ( AI* _ai, tnstream& stream );
86  Vehicle* getTargetUnit ( ) const { return ai->getMap()->getUnit ( targetUnitID );};
87  Vehicle* getServiceUnit ( ) const { return ai->getMap()->getUnit ( serviceUnitID );};
88  void setServiceUnit ( Vehicle* veh );
89  int possible ( Vehicle* supplier );
90  bool execute1st ( Vehicle* supplier );
91  bool timeOut ( );
92  bool canWait ( );
93 
94  void serviceFailed() { failure++; };
95  bool completelyFailed();
96 
97  bool serviceUnitExists();
98 
99  static void releaseServiceUnit ( ServiceOrder& so );
100 
101  void write ( tnstream& stream ) const;
102  void read ( tnstream& read );
103 
104  static bool targetDestroyed ( const ServiceOrder& so )
105  {
106  return !so.getTargetUnit();
107  };
108  static bool invalid ( const ServiceOrder& so );
109  bool valid ( ) const;
110  static void activate( ServiceOrder& so );
111 
112  bool operator==( const ServiceOrder& so ) const;
113  bool operator!=( const ServiceOrder& so ) const;
114 
115 
116  ~ServiceOrder ();
117  };
118  friend class ServiceOrder;
119 
120  void removeServiceOrdersForUnit ( const Vehicle* veh );
121 
122  class ServiceTargetEquals : public unary_function<ServiceOrder&,bool> {
123  const Vehicle* target;
124  public:
125  explicit ServiceTargetEquals ( const Vehicle* _target ) : target ( _target ) {};
126  bool operator() (const ServiceOrder& so ) const;
127  };
128 
129 
131  set<Vehicle*> unitsWorkedInTactics;
132 
133  static bool vehicleValueComp ( const Vehicle* v1, const Vehicle* v2 );
134  static bool buildingValueComp ( const Building* v1, const Building* v2 );
135 
136  typedef list<ServiceOrder> ServiceOrderContainer;
137  ServiceOrderContainer serviceOrders;
139  void issueServices ( );
140 
142  ServiceOrder& issueService ( ServiceOrder::Service requiredService, int UnitID, int pos = -1 );
143 
144  ServiceOrder& issueRefuelOrder ( Vehicle* veh, bool returnImmediately );
145  void runServiceUnit ( Vehicle* supplyUnit );
146 
147  class RefuelConstraint {
148  AI& ai;
149  Vehicle* veh;
150  AStar3D* ast;
151  typedef map<int, Building*> ReachableBuildings;
152  ReachableBuildings reachableBuildings;
153 
154  typedef map<int, MapCoordinate3D> LandingPositions;
155  LandingPositions landingPositions;
156  bool positionsCalculated;
157  int maxMove;
158  public:
159  RefuelConstraint ( AI& ai_, Vehicle* veh_, int maxMove_ = -1 ) : ai ( ai_ ), veh ( veh_ ), ast(NULL), positionsCalculated(false), maxMove ( maxMove_ ) {};
160  MapCoordinate3D getNearestRefuellingPosition ( bool buildingRequired, bool refuel, bool repair );
161  bool returnFromPositionPossible ( const MapCoordinate3D& pos, int theoreticalFuel = -1 );
163  void findPath( bool markTemps=true);
164  static bool necessary (const Vehicle* veh, AI& ai );
165  AStar3D* getAst() { return ast; };
166  ~RefuelConstraint() { if (ast) delete ast; };
167  };
168  friend class RefuelConstraint;
169 
170  bool runUnitTask ( Vehicle* veh );
171  // void searchServices ( );
172 
173  class FieldInformation {
174  public:
175  AiThreat threat;
176  int control;
177  int units[8];
178  void reset ( );
179  FieldInformation ( ) { reset(); };
180  };
181 
182  FieldInformation* fieldInformation;
183  int fieldNum;
184  AiThreat& getFieldThreat ( int x, int y );
185  FieldInformation& getFieldInformation ( int x, int y );
186 
187  class CheckFieldRecon : public SearchFields {
188  protected:
189  void testfield ( const MapCoordinate& mc ) ;
190  int ownFields[3];
191  int enemyFields[3];
192  int player;
193  AI* ai;
194  public:
195  CheckFieldRecon ( AI* _ai );
196  int run ( int x, int y);
197  };
198  friend class CheckFieldRecon;
199 
200 
201  MapCoordinate3D findServiceBuilding ( const ServiceOrder& so, int* distance = NULL );
202 
203  void checkConquer( );
204  void runReconUnits();
205 
207  bool checkReConquer ( Building* bld, Vehicle* veh );
208  float getCaptureValue ( const Building* bld, int travelTime );
209  float getCaptureValue ( const Building* bld, Vehicle* veh );
210 
211  class BuildingCapture {
212  public:
213  enum BuildingCaptureState { conq_noUnit,
214  conq_unitNotConq,
215  conq_conqUnit,
216  conq_unreachable } state;
217  int unit;
218  vector<int> guards;
219 
220  float captureValue;
221  int nearestUnit;
222 
223  void write ( tnstream& stream ) const;
224  void read ( tnstream& stream );
225 
226  BuildingCapture ( ) {
227  state = conq_noUnit;
228  unit = 0;
229  nearestUnit = 0;
230  captureValue = 0;
231  };
232  };
233 
234  class BuildingValueComp : public binary_function<Building*,Building*,bool> {
235  AI* ai;
236  public:
237  explicit BuildingValueComp ( AI* _ai ) : ai ( _ai ) {};
238  bool operator() (const Building*& a, const Building*& b ) const {
239  return ai->buildingCapture[ a->getEntry() ].captureValue > ai->buildingCapture[ b->getEntry() ].captureValue;
240  };
241  };
242  friend class BuildingValueComp;
243 
244  typedef map<MapCoordinate,BuildingCapture> BuildingCaptureContainer;
245  BuildingCaptureContainer buildingCapture;
246 
247 
248  void calculateFieldInformation ( void );
249  void calculateFieldThreats_SinglePosition ( Vehicle* eht, int x, int y );
250  class WeaponThreatRange : public SearchFields {
251  Vehicle* veh;
252  int weap, height;
253  AiThreat* threat;
254  AI* ai;
255  void testfield ( const MapCoordinate& mc );
256  public:
257  void run ( Vehicle* _veh, int x, int y, AiThreat* _threat );
258  WeaponThreatRange( AI* _ai ) : SearchFields ( _ai->getMap()), ai ( _ai ) {};
259  };
260 
261 
262  struct Config {
263  // int movesearchshortestway; /* krzesten oder nur irgendeinen */
264  int lookIntoTransports; /* gegnerische transporter einsehen */
265  int lookIntoBuildings;
266  int wholeMapVisible;
267  float aggressiveness; // 1: units are equally worth ; 2
268  int damageLimit;
269  Resources resourceLimit;
270  int ammoLimit;
272  int maxCaptureTime;
273 
275  int maxTactTime;
276  int waitForResourcePlus;
277  } config;
278 
279  public:
280  class MoveVariant {
281  public:
291  int weapNum;
292  float result;
293  int moveDist;
294  bool neighbouringFieldsReachable[ sidenum ]; // used for the hemming tactic
296  bool operator< ( const MoveVariant& a ) const;
297  bool operator> ( const MoveVariant& a ) const;
298  };
299  static bool moveVariantComp ( const AI::MoveVariant* mv1, const AI::MoveVariant* mv2 );
300  private:
301 
302  typedef vector<MoveVariant> MoveVariantContainer;
303 
304  class AiResult {
305  public:
306  int unitsMoved;
307  int unitsWaiting;
308  int unitsDestroyed;
309  AiResult ( ) : unitsMoved ( 0 ), unitsWaiting ( 0 ), unitsDestroyed( 0 ) {};
310 
311  AiResult& operator+= ( const AiResult& a ) {
312  unitsMoved += a.unitsMoved;
313  unitsWaiting += a.unitsWaiting;
314  unitsDestroyed += a.unitsDestroyed;
315  return *this;
316  };
317  };
318 
319 
320 
321  class TargetVector : public std::vector<MoveVariant*> {
322  public:
323  ~TargetVector() {
324  for ( iterator it = begin(); it != end(); it++ )
325  delete *it;
326  };
327  };
328 
329  bool moveUnit ( Vehicle* veh, const MapCoordinate3D& destination, bool intoBuildings = true, bool intoTransports = true );
330 
331  void getAttacks ( AStar3D& vm, Vehicle* veh, TargetVector& tv, int hemmingBonus, bool justOne = false, bool executeService = true );
332  void searchTargets ( Vehicle* veh, const MapCoordinate3D& pos, TargetVector& tl, int moveDist, AStar3D& vm, int hemmingBonus );
333  bool targetsNear( Vehicle* veh );
334 
335  AiResult executeMoveAttack ( Vehicle* veh, TargetVector& tv );
336  int getDirForBestTacticsMove ( const Vehicle* veh, TargetVector& tv );
337  MapCoordinate getDestination ( Vehicle* veh );
338  AiResult moveToSavePlace ( Vehicle* veh, int preferredHeight = -1 );
339  int getBestHeight ( Vehicle* veh );
340  float getAttackValue ( const tfight& battle, Vehicle* attackingUnit, Vehicle* attackedUnit, float factor = 1 );
341 
348  int changeVehicleHeight ( Vehicle* veh, int preferredDirection = -1 );
349 
350  void calculateThreat ( const VehicleType* vt);
351  void calculateThreat ( Vehicle* eht );
352  void calculateThreat ( Building* bld );
353  void calculateThreat ( Building* bld, int player );
354  int getValue( Vehicle* v );
355 
356 
357  static AiParameter::JobList chooseJob ( const VehicleType* typ );
359 
365  void calculateAllThreats( void );
366  AiResult tactics( void );
367  void tactics_findBestAttackOrder ( Vehicle** units, int* attackOrder, Vehicle* enemy, int depth, int damage, int& finalDamage, int* finalOrder, int& finalAttackNum );
368  void tactics_findBestAttackUnits ( const MoveVariantContainer& mvc, MoveVariantContainer::iterator& m, Vehicle** positions, float value, Vehicle** finalposition, float& finalvalue, int unitsPositioned, int recursionDepth, int startTime );
369 
370  class UnitDistribution {
371  public:
372  static const int groupCount = 6;
373  enum Group { attack, rangeattack, conquer, other, recon, service };
374  bool calculated;
375  float group[groupCount];
376  UnitDistribution( ) : calculated ( false ) { for ( int i = 0; i < groupCount; i++ ) group[i] = 0; };
377  void read( tnstream& stream );
378  void write ( tnstream& stream ) const;
379  };
380  UnitDistribution originalUnitDistribution;
381  UnitDistribution::Group getUnitDistributionGroup ( Vehicle* veh );
382  UnitDistribution::Group getUnitDistributionGroup ( VehicleType* veh );
383 
384  UnitDistribution calcUnitDistribution();
385  struct ProductionRating {
386  const VehicleType* vt;
387  Building* bld;
388  float rating;
389  bool operator< ( const ProductionRating& pr ) { return rating < pr.rating; };
390  };
391 
392  typedef map<int,pair<float,float> > UnitTypeSuccess; // first: enemy value, second: own value
393  UnitTypeSuccess unitTypeSuccess;
394 
396  AI& ai;
397  float ownValue;
398  int ownTypeID;
399  float enemyValue;
400  int orgOwnDamage;
401  int orgEnemyDamage;
402  int enemyID;
403  int ownID;
404  Vehicle* attacker;
405  Vehicle* target;
406  public:
407  VehicleTypeEfficiencyCalculator ( AI& _ai, Vehicle* _attacker, Vehicle* _target );
408  void calc();
409  };
411 
412  void production();
413 
414  AiResult strategy();
415  AiResult buildings ( int process );
416  AiResult transports ( int process );
417  AiResult container ( ContainerBase* cb );
418  AiResult executeServices ();
419  void setup();
420 
421  void reset();
422 
423  typedef map<MapCoordinate,int> ReconPositions;
424  ReconPositions reconPositions;
425  void calcReconPositions();
426 
427  class Section {
428  AI* ai;
429  public:
430  int x1,y1,x2,y2;
431  int xp, yp;
432  int centerx, centery;
433  int units_heading_here;
434 
435  int numberOfFields;
436  AiThreat absUnitThreat;
437  AiThreat avgUnitThreat;
438  AiThreat absFieldThreat;
439  AiThreat avgFieldThreat;
440  float value[ aiValueTypeNum ];
441 
442  int numberOfAccessibleFields ( const Vehicle* veh );
443  void init ( int _x, int _y, int xsize, int ysize, int _xp, int _yp );
444  void init ( AI* _ai, int _x, int _y, int xsize, int ysize, int _xp, int _yp );
445  Section ( AI* _ai ) : ai ( _ai ) {};
446  Section ( ) { ai = NULL; }; //
447  };
448  friend class Section;
449 
450  class Sections {
451  AI* ai;
452  Section* section;
453  MapCoordinate getAlternativeField( const MapCoordinate& pos, map<MapCoordinate,int>* destinationCounter, int height, AStar3D* ast );
454  public:
455  int sizeX ;
456  int sizeY ;
457  int numX ;
458  int numY ;
459  void calculate ( void );
460  Section& getForCoordinate ( int xc, int yc );
461  Section& getForPos ( int xn, int yn );
462 
463  // secondRun should only be used when this function calls itself recursively
464  Section* getBest ( int pass, Vehicle* veh, MapCoordinate3D* dest = NULL, bool allowRefuellOrder = false, bool secondRun = false, map<MapCoordinate,int>* destinationCounter = NULL);
465  Sections ( AI* _ai );
466  void reset();
467  ~Sections();
468  } sections;
469  friend class Sections;
470 
471  void checkKeys ( void );
472  void removeDisplay();
473 
474  void diplomacy ();
475 
476  void checkGameEvents();
477 
478  public:
479  AI ( GameMap* _map, int _player ) ;
480 
481  void run ( MapDisplayInterface* mapDisplay ) { run ( false, mapDisplay );};
483  void run ( bool benchmark, MapDisplayInterface* mapDisplay );
484 
486  GameMap* getMap ( void ) { return activemap; };
487  const GameMap* getMap ( void ) const { return activemap; };
488 
490  int getPlayerNum ( void ) { return player; };
491 
492  Player& getPlayer ( void ) { return getMap()->player[player]; };
493  Player& getPlayer ( int player ) { return getMap()->player[player]; };
494  Player& getPlayer ( PlayerID id ) { return getMap()->player[id.getID()]; };
495  void showFieldInformation ( int x, int y );
496  //inline bool isRunning ( void ) {return _isRunning;};
497  inline bool isRunning ( void ) {return getMap()->playerAiRunning[player];};
498  inline bool isRunning ( void ) const {return getMap()->playerAiRunning[player];};
499  inline void isRunning ( bool b ) { getMap()->playerAiRunning[player] = b;};
500 
506  inline VisibilityStates getVision ( void ) { return getMap()->playerAiVision[player]; };
507  inline VisibilityStates getVision ( void ) const { return getMap()->playerAiVision[player]; };
508  inline void setVision ( VisibilityStates v ) { getMap()->playerAiVision[player] = v; };
509 
510  void read ( tnstream& stream );
511  void write ( tnstream& stream ) const ;
512 
514  ~AI ( );
515  };
516 
517 //extern bool operator> ( const AI::MoveVariant& mv1, const AI::MoveVariant& mv2 );
518 //extern bool operator< ( const AI::MoveVariant& mv1, const AI::MoveVariant& mv2 );
519 
520 
521 #endif
the time in ASC, measured in turns and moves
Definition: typen.h:178
bool operator==(const AStar3D::Node &a, const AStar3D::Node &b)
Definition: astar2.cpp:122
friend class Sections
Definition: ai.h:469
void isRunning(bool b)
Definition: ai.h:499
GameMap * getMap(void)
returns the map this AI runson
Definition: ai.h:486
void run(MapDisplayInterface *mapDisplay)
Definition: ai.h:481
static bool moveVariantComp(const AI::MoveVariant *mv1, const AI::MoveVariant *mv2)
Definition: tactics.cpp:178
int moveDist
Definition: ai.h:293
VisibilityStates
the different states that a player's view on a field can have
Definition: typen.h:403
MapCoordinate3D getEntry() const
returns the position of the buildings entry
Definition: buildings.cpp:410
int weapNum
Definition: ai.h:291
vector< AiParameter::Job > JobList
Player & getPlayer(int player)
Definition: ai.h:493
void checkGameEvents(GameMap *map, const Command &command)
Definition: sg.cpp:1367
int damageAfterAttack
Definition: ai.h:284
The interface for all kinds of IO stream.
Definition: ai.h:44
int enemyOrgDamage
Definition: ai.h:289
~AI()
Definition: base.cpp:610
Vehicle * attacker
Definition: ai.h:288
friend class CheckFieldRecon
Definition: ai.h:198
AI(GameMap *_map, int _player)
Definition: base.cpp:28
const int aiValueTypeNum
how many different target types are there?
const int sidenum
the number of sides that a field has; is now fixed at 6;
Definition: typen.h:438
friend class BuildingValueComp
Definition: ai.h:242
bool playerAiRunning[9]
Definition: gamemap.h:192
int getPlayerNum(void)
returns the number of the player which is controlled by this ai
Definition: ai.h:490
const GameMap * getMap(void) const
Definition: ai.h:487
The class describing properties that are common to all vehicles of a certain kind.
Definition: vehicletype.h:177
friend class RefuelConstraint
Definition: ai.h:168
Player & getPlayer(PlayerID id)
Definition: ai.h:494
void setVision(VisibilityStates v)
Definition: ai.h:508
bool isRunning(void) const
Definition: ai.h:498
bool neighbouringFieldsReachable[sidenum]
Definition: ai.h:294
friend class Section
Definition: ai.h:448
VisibilityStates getVision(void) const
Definition: ai.h:507
int attacky
Definition: ai.h:286
Coordinate on the twodimensional map.
Definition: typen.h:202
the threat that a unit poses against other units.
Player & getPlayer(void)
Definition: ai.h:492
friend class ServiceOrder
Definition: ai.h:118
float positionThreat
Definition: ai.h:295
searches fields in hexagonal "circles" around a field and calls testfield for each field ...
Definition: mapalgorithms.h:28
MapCoordinate3D movePos
Definition: ai.h:285
friend class VehicleTypeEfficiencyCalculator
Definition: ai.h:410
Vehicle * getUnit(int x, int y, int nwid)
Definition: gamemap.cpp:1215
Player player[9]
Definition: gamemap.h:253
int damageAfterMove
Definition: ai.h:283
void attack(Vehicle *veh, const MapCoordinate &target)
VisibilityStates getVision(void)
the AI uses a different vision than human player, to counter the fact that a human player can "know" ...
Definition: ai.h:506
Definition: attack.h:83
int enemyDamage
Definition: ai.h:290
Coordinate on the map including height.
Definition: typen.h:238
bool isRunning(void)
Definition: ai.h:497
int attackx
Definition: ai.h:286
A 3D path finding algorithm, based on the 2D algorithm by Amit J. Patel.
Definition: astar2.h:19
Vehicle * enemy
Definition: ai.h:287
void read(tnstream &stream)
Definition: base.cpp:477
GameMap * getMap() const
bool operator<(const MoveVariant &a) const
Definition: tactics.cpp:155
The parent class of Vehicle and Building; The name Container originates from Battle Isle...
Definition: containerbase.h:40
An actual building on the map, which references a BuildingType Buildings have an owner,.
Definition: buildings.h:38
int orgDamage
Definition: ai.h:282
the different players in ASC. There may be 8 players (0..7) and neutral units (8) ...
Definition: player.h:99
Resources are basically the currency of ASC.
Definition: typen.h:97
bool operator>(const MoveVariant &a) const
Definition: tactics.cpp:147
VisibilityStates playerAiVision[9]
Definition: gamemap.h:193
convenience-class which automatically determines the Player of units, buildings and other game object...
Definition: player.h:40
void write(tnstream &stream) const
Definition: base.cpp:551
Context getContext()
Definition: base.cpp:597
The map. THE central structure of ASC, which holds everything not globally available together...
Definition: gamemap.h:182
float result
Definition: ai.h:292
void showFieldInformation(int x, int y)
Definition: base.cpp:378