VCAI.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #pragma once
  2. typedef const int3& crint3;
  3. typedef const std::string& crstring;
  4. //provisional class for AI to store a reference to an owned hero object
  5. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  6. struct HeroPtr
  7. {
  8. const CGHeroInstance *h;
  9. int hid; //hero id (object subID or type ID)
  10. public:
  11. std::string name;
  12. HeroPtr();
  13. HeroPtr(const CGHeroInstance *H);
  14. ~HeroPtr();
  15. operator bool() const
  16. {
  17. return validAndSet();
  18. }
  19. bool operator<(const HeroPtr &rhs) const;
  20. const CGHeroInstance *operator->() const;
  21. const CGHeroInstance *operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  22. const CGHeroInstance *get(bool doWeExpectNull = false) const;
  23. bool validAndSet() const;
  24. };
  25. enum BattleState
  26. {
  27. NO_BATTLE,
  28. UPCOMING_BATTLE,
  29. ONGOING_BATTLE,
  30. ENDING_BATTLE
  31. };
  32. class AIStatus
  33. {
  34. boost::mutex mx;
  35. boost::condition_variable cv;
  36. BattleState battle;
  37. std::map<int, std::string> remainingQueries;
  38. std::map<int, int> requestToQueryID; //IDs of answer-requests sent to server => query ids (so we can match answer confirmation from server to the query)
  39. bool havingTurn;
  40. public:
  41. AIStatus();
  42. ~AIStatus();
  43. void setBattle(BattleState BS);
  44. BattleState getBattle();
  45. void addQuery(int ID, std::string description);
  46. void removeQuery(int ID);
  47. int getQueriesCount();
  48. void startedTurn();
  49. void madeTurn();
  50. void waitTillFree();
  51. bool haveTurn();
  52. void attemptedAnsweringQuery(int queryID, int answerRequestID);
  53. void receivedAnswerConfirmation(int answerRequestID, int result);
  54. };
  55. enum EGoals
  56. {
  57. INVALID = -1,
  58. WIN, DO_NOT_LOSE, CONQUER, BUILD, //build needs to get a real reasoning
  59. EXPLORE, GATHER_ARMY, BOOST_HERO,
  60. RECRUIT_HERO,
  61. BUILD_STRUCTURE, //if hero set, then in visited town
  62. COLLECT_RES,
  63. OBJECT_GOALS_BEGIN,
  64. GET_OBJ, //visit or defeat or collect the object
  65. FIND_OBJ, //find and visit any obj with objid + resid //TODO: consider universal subid for various types (aid, bid)
  66. GET_ART_TYPE,
  67. //BUILD_STRUCTURE,
  68. ISSUE_COMMAND,
  69. //hero
  70. //VISIT_OBJ, //hero + tile
  71. VISIT_TILE, //tile, in conjunction with hero elementar; assumes tile is reachable
  72. CLEAR_WAY_TO,
  73. DIG_AT_TILE //elementar with hero on tile
  74. };
  75. struct CGoal;
  76. typedef CGoal TSubgoal;
  77. #define SETTER(type, field) CGoal &set ## field(const type &rhs) { field = rhs; return *this; }
  78. #if 0
  79. #define SETTER
  80. #endif // _DEBUG
  81. enum {LOW_PR = -1};
  82. struct CGoal
  83. {
  84. EGoals goalType;
  85. bool isElementar; SETTER(bool, isElementar)
  86. bool isAbstract; SETTER(bool, isAbstract) //allows to remember abstract goals
  87. int priority; SETTER(bool, priority)
  88. virtual TSubgoal whatToDoToAchieve();
  89. CGoal(EGoals goal = INVALID) : goalType(goal)
  90. {
  91. priority = 0;
  92. isElementar = false;
  93. isAbstract = false;
  94. value = 0;
  95. objid = -1;
  96. aid = -1;
  97. resID = -1;
  98. tile = int3(-1, -1, -1);
  99. town = NULL;
  100. }
  101. bool invalid() const;
  102. static TSubgoal goVisitOrLookFor(const CGObjectInstance *obj); //if obj is NULL, then we'll explore
  103. static TSubgoal lookForArtSmart(int aid); //checks non-standard ways of obtaining art (merchants, quests, etc.)
  104. static TSubgoal tryRecruitHero();
  105. int value; SETTER(int, value)
  106. int resID; SETTER(int, resID)
  107. int objid; SETTER(int, objid)
  108. int aid; SETTER(int, aid)
  109. int3 tile; SETTER(int3, tile)
  110. HeroPtr hero; SETTER(HeroPtr, hero)
  111. const CGTownInstance *town; SETTER(CGTownInstance *, town)
  112. int bid; SETTER(int, bid)
  113. };
  114. enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
  115. struct SectorMap
  116. {
  117. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  118. struct Sector
  119. {
  120. int id;
  121. std::vector<int3> tiles;
  122. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  123. bool water; //all tiles of sector are land or water
  124. Sector()
  125. {
  126. id = -1;
  127. }
  128. };
  129. bool valid; //some kind of lazy eval
  130. std::map<int3, int3> parent;
  131. std::vector<std::vector<std::vector<unsigned char>>> sector;
  132. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  133. std::map<int, Sector> infoOnSectors;
  134. SectorMap();
  135. void update();
  136. void clear();
  137. void exploreNewSector(crint3 pos, int num);
  138. void write(crstring fname);
  139. unsigned char &retreiveTile(crint3 pos);
  140. void makeParentBFS(crint3 source);
  141. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  142. };
  143. struct CIssueCommand : CGoal
  144. {
  145. boost::function<bool()> command;
  146. CIssueCommand(boost::function<bool()> _command): CGoal(ISSUE_COMMAND), command(_command) {}
  147. };
  148. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  149. // This class stores object id, so we can detect when we lose access to the underlying object.
  150. struct ObjectIdRef
  151. {
  152. int id;
  153. const CGObjectInstance *operator->() const;
  154. operator const CGObjectInstance *() const;
  155. ObjectIdRef(int _id);
  156. ObjectIdRef(const CGObjectInstance *obj);
  157. bool operator<(const ObjectIdRef &rhs) const;
  158. };
  159. class ObjsVector : public std::vector<ObjectIdRef>
  160. {
  161. private:
  162. };
  163. class VCAI : public CAdventureAI
  164. {
  165. //internal methods for town development
  166. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  167. bool tryBuildStructure(const CGTownInstance * t, int building, unsigned int maxDays=0);
  168. //try build ANY unbuilt structure
  169. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays=0);
  170. //try build first unbuilt structure
  171. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays=0);
  172. public:
  173. friend class FuzzyHelper;
  174. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  175. std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  176. std::map<HeroPtr, std::vector<const CGTownInstance *> > townVisitsThisWeek;
  177. std::map<HeroPtr, CGoal> lockedHeroes; //TODO: allow non-elementar objectives
  178. std::map<HeroPtr, std::vector<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
  179. std::vector<const CGObjectInstance *> visitableObjs;
  180. std::vector<const CGObjectInstance *> alreadyVisited;
  181. std::vector<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  182. TResources saving;
  183. AIStatus status;
  184. std::string battlename;
  185. CCallback *myCb;
  186. VCAI(void);
  187. ~VCAI(void);
  188. CGObjectInstance * visitedObject; //remember currently viisted object
  189. boost::thread *makingTurn;
  190. void tryRealize(CGoal g);
  191. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  192. int3 explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles);
  193. void recruitHero();
  194. virtual void init(CCallback * CB);
  195. virtual void yourTurn();
  196. virtual void heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, int queryID) OVERRIDE; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
  197. virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, int queryID) OVERRIDE; //TODO
  198. virtual void showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel) OVERRIDE; //Show a dialog, player must take decision. If selection then he has to choose between one of given components, if cancel he is allowed to not choose. After making choice, CCallback::selectionMade should be called with number of selected component (1 - n) or 0 for cancel (if allowed) and askID.
  199. virtual void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, int queryID) OVERRIDE; //all stacks operations between these objects become allowed, interface has to call onEnd when done
  200. virtual void serialize(COSer<CSaveFile> &h, const int version) OVERRIDE; //saving
  201. virtual void serialize(CISer<CLoadFile> &h, const int version) OVERRIDE; //loading
  202. virtual void finish() OVERRIDE;
  203. virtual void availableCreaturesChanged(const CGDwelling *town) OVERRIDE;
  204. virtual void heroMoved(const TryMoveHero & details) OVERRIDE;
  205. virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) OVERRIDE;
  206. virtual void heroInGarrisonChange(const CGTownInstance *town) OVERRIDE;
  207. virtual void centerView(int3 pos, int focusTime) OVERRIDE;
  208. virtual void tileHidden(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  209. virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) OVERRIDE;
  210. virtual void artifactAssembled(const ArtifactLocation &al) OVERRIDE;
  211. virtual void showTavernWindow(const CGObjectInstance *townOrTavern) OVERRIDE;
  212. virtual void showThievesGuildWindow (const CGObjectInstance * obj) OVERRIDE;
  213. virtual void playerBlocked(int reason) OVERRIDE;
  214. virtual void showPuzzleMap() OVERRIDE;
  215. virtual void showShipyardDialog(const IShipyard *obj) OVERRIDE;
  216. virtual void gameOver(ui8 player, bool victory) OVERRIDE;
  217. virtual void artifactPut(const ArtifactLocation &al) OVERRIDE;
  218. virtual void artifactRemoved(const ArtifactLocation &al) OVERRIDE;
  219. virtual void stacksErased(const StackLocation &location) OVERRIDE;
  220. virtual void artifactDisassembled(const ArtifactLocation &al) OVERRIDE;
  221. virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) OVERRIDE;
  222. virtual void availableArtifactsChanged(const CGBlackMarket *bm = NULL) OVERRIDE;
  223. virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) OVERRIDE;
  224. virtual void tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos) OVERRIDE;
  225. virtual void heroExchangeStarted(si32 hero1, si32 hero2) OVERRIDE;
  226. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) OVERRIDE;
  227. virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) OVERRIDE;
  228. virtual void heroMovePointsChanged(const CGHeroInstance * hero) OVERRIDE;
  229. virtual void stackChangedType(const StackLocation &location, const CCreature &newType) OVERRIDE;
  230. virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) OVERRIDE;
  231. virtual void newObject(const CGObjectInstance * obj) OVERRIDE;
  232. virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) OVERRIDE;
  233. virtual void playerBonusChanged(const Bonus &bonus, bool gain) OVERRIDE;
  234. virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) OVERRIDE;
  235. virtual void heroCreated(const CGHeroInstance*) OVERRIDE;
  236. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) OVERRIDE;
  237. virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) OVERRIDE;
  238. virtual void requestRealized(PackageApplied *pa) OVERRIDE;
  239. virtual void receivedResource(int type, int val) OVERRIDE;
  240. virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) OVERRIDE;
  241. virtual void objectRemoved(const CGObjectInstance *obj) OVERRIDE;
  242. virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  243. virtual void heroManaPointsChanged(const CGHeroInstance * hero) OVERRIDE;
  244. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) OVERRIDE;
  245. virtual void battleResultsApplied() OVERRIDE;
  246. virtual void objectPropertyChanged(const SetObjectProperty * sop) OVERRIDE;
  247. virtual void buildChanged(const CGTownInstance *town, int buildingID, int what) OVERRIDE;
  248. virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) OVERRIDE;
  249. virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) OVERRIDE;
  250. virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) OVERRIDE;
  251. virtual void battleEnd(const BattleResult *br) OVERRIDE;
  252. void makeTurn();
  253. void makeTurnInternal();
  254. void performTypicalActions();
  255. void buildArmyIn(const CGTownInstance * t);
  256. void striveToGoal(const CGoal &ultimateGoal);
  257. void endTurn();
  258. void wander(HeroPtr h);
  259. void setGoal(HeroPtr h, const CGoal goal);
  260. void setGoal(HeroPtr h, EGoals goalType = INVALID);
  261. void completeGoal (const CGoal goal); //safely removes goal from reserved hero
  262. void striveToQuest (const QuestInfo &q);
  263. void recruitHero(const CGTownInstance * t);
  264. std::vector<const CGObjectInstance *> getPossibleDestinations(HeroPtr h);
  265. void buildStructure(const CGTownInstance * t);
  266. //void recruitCreatures(const CGTownInstance * t);
  267. void recruitCreatures(const CGDwelling * d);
  268. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  269. void moveCreaturesToHero(const CGTownInstance * t);
  270. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  271. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  272. bool moveHeroToTile(int3 dst, HeroPtr h);
  273. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  274. void waitTillFree();
  275. void addVisitableObj(const CGObjectInstance *obj);
  276. void markObjectVisited (const CGObjectInstance *obj);
  277. void reserveObject (HeroPtr h, const CGObjectInstance *obj);
  278. //void removeVisitableObj(const CGObjectInstance *obj);
  279. void validateVisitableObjs();
  280. void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
  281. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  282. const CGObjectInstance *lookForArt(int aid) const;
  283. bool isAccessible(const int3 &pos);
  284. HeroPtr getHeroWithGrail() const;
  285. const CGObjectInstance *getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate);
  286. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  287. const CGTownInstance *findTownWithTavern() const;
  288. std::vector<HeroPtr> getUnblockedHeroes() const;
  289. HeroPtr primaryHero() const;
  290. TResources estimateIncome() const;
  291. bool containsSavedRes(const TResources &cost) const;
  292. void checkHeroArmy (HeroPtr h);
  293. void requestSent(const CPackForServer *pack, int requestID) OVERRIDE;
  294. void answerQuery(int queryID, int selection);
  295. //special function that can be called ONLY from game events handling thread and will send request ASAP
  296. void requestActionASAP(boost::function<void()> whatToDo);
  297. };
  298. template<int id>
  299. bool objWithID(const CGObjectInstance *obj)
  300. {
  301. return obj->ID == id;
  302. }
  303. bool isBlockedBorderGate(int3 tileToHit);
  304. bool isWeeklyRevisitable (const CGObjectInstance * obj);
  305. bool shouldVisit (HeroPtr h, const CGObjectInstance * obj);