VCAI.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #pragma once
  2. #include "AIUtility.h"
  3. #include "Goals.h"
  4. #include "../../lib/AI_Base.h"
  5. #include "../../CCallback.h"
  6. #include "../../lib/CDefObjInfoHandler.h"
  7. #include "../../lib/CThreadHelper.h"
  8. #include "../../lib/VCMI_Lib.h"
  9. #include "../../lib/CBuildingHandler.h"
  10. #include "../../lib/CCreatureHandler.h"
  11. #include "../../lib/CTownHandler.h"
  12. #include "../../lib/CSpellHandler.h"
  13. #include "../../lib/CObjectHandler.h"
  14. #include "../../lib/Connection.h"
  15. #include "../../lib/CGameState.h"
  16. #include "../../lib/mapping/CMap.h"
  17. #include "../../lib/NetPacks.h"
  18. #include "../../lib/CondSh.h"
  19. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  20. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  21. struct QuestInfo;
  22. /*
  23. * VCAI.h, part of VCMI engine
  24. *
  25. * Authors: listed in file AUTHORS in main folder
  26. *
  27. * License: GNU General Public License v2.0 or later
  28. * Full text of license available in license.txt file, in main folder
  29. *
  30. */
  31. class AIStatus
  32. {
  33. boost::mutex mx;
  34. boost::condition_variable cv;
  35. BattleState battle;
  36. std::map<QueryID, std::string> remainingQueries;
  37. std::map<int, QueryID> requestToQueryID; //IDs of answer-requests sent to server => query ids (so we can match answer confirmation from server to the query)
  38. std::vector<const CGObjectInstance*> objectsBeingVisited;
  39. bool ongoingHeroMovement;
  40. bool havingTurn;
  41. public:
  42. AIStatus();
  43. ~AIStatus();
  44. void setBattle(BattleState BS);
  45. void setMove(bool ongoing);
  46. BattleState getBattle();
  47. void addQuery(QueryID ID, std::string description);
  48. void removeQuery(QueryID ID);
  49. int getQueriesCount();
  50. void startedTurn();
  51. void madeTurn();
  52. void waitTillFree();
  53. bool haveTurn();
  54. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  55. void receivedAnswerConfirmation(int answerRequestID, int result);
  56. void heroVisit(const CGObjectInstance *obj, bool started);
  57. template <typename Handler> void serialize(Handler &h, const int version)
  58. {
  59. h & battle & remainingQueries & requestToQueryID & havingTurn;
  60. }
  61. };
  62. enum {NOT_VISIBLE = 0, NOT_CHECKED = 1, NOT_AVAILABLE};
  63. struct SectorMap
  64. {
  65. //a sector is set of tiles that would be mutually reachable if all visitable objs would be passable (incl monsters)
  66. struct Sector
  67. {
  68. int id;
  69. std::vector<int3> tiles;
  70. std::vector<int3> embarkmentPoints; //tiles of other sectors onto which we can (dis)embark
  71. bool water; //all tiles of sector are land or water
  72. Sector()
  73. {
  74. id = -1;
  75. }
  76. };
  77. bool valid; //some kind of lazy eval
  78. std::map<int3, int3> parent;
  79. std::vector<std::vector<std::vector<unsigned char>>> sector;
  80. //std::vector<std::vector<std::vector<unsigned char>>> pathfinderSector;
  81. std::map<int, Sector> infoOnSectors;
  82. SectorMap();
  83. void update();
  84. void clear();
  85. void exploreNewSector(crint3 pos, int num);
  86. void write(crstring fname);
  87. unsigned char &retreiveTile(crint3 pos);
  88. void makeParentBFS(crint3 source);
  89. int3 firstTileToGet(HeroPtr h, crint3 dst); //if h wants to reach tile dst, which tile he should visit to clear the way?
  90. };
  91. class VCAI : public CAdventureAI
  92. {
  93. //internal methods for town development
  94. //try build an unbuilt structure in maxDays at most (0 = indefinite)
  95. bool tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=0);
  96. //try build ANY unbuilt structure
  97. bool tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=0);
  98. //try build first unbuilt structure
  99. bool tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays=0);
  100. public:
  101. friend class FuzzyHelper;
  102. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  103. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  104. std::map<HeroPtr, std::vector<const CGTownInstance *> > townVisitsThisWeek;
  105. std::map<HeroPtr, Goals::CGoal> lockedHeroes; //TODO: allow non-elementar objectives
  106. std::map<HeroPtr, std::vector<const CGObjectInstance *> > reservedHeroesMap; //objects reserved by specific heroes
  107. std::vector<const CGObjectInstance *> visitableObjs;
  108. std::vector<const CGObjectInstance *> alreadyVisited;
  109. std::vector<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  110. TResources saving;
  111. AIStatus status;
  112. std::string battlename;
  113. shared_ptr<CCallback> myCb;
  114. unique_ptr<boost::thread> makingTurn;
  115. VCAI(void);
  116. ~VCAI(void);
  117. void tryRealize(Goals::CGoal g);
  118. void tryRealize(Goals::Explore g);
  119. void tryRealize(Goals::RecruitHero g);
  120. void tryRealize(Goals::VisitTile g);
  121. void tryRealize(Goals::VisitHero g);
  122. void tryRealize(Goals::BuildThis g);
  123. void tryRealize(Goals::DigAtTile g);
  124. void tryRealize(Goals::CollectRes g);
  125. void tryRealize(Goals::Build g);
  126. void tryRealize(Goals::Invalid g);
  127. int3 explorationBestNeighbour(int3 hpos, int radius, HeroPtr h);
  128. int3 explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles);
  129. void recruitHero();
  130. virtual std::string getBattleAIName() const override;
  131. virtual void init(shared_ptr<CCallback> CB) override;
  132. virtual void yourTurn() override;
  133. virtual void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id
  134. virtual void commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  135. virtual void showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID 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.
  136. virtual void showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID) override; //all stacks operations between these objects become allowed, interface has to call onEnd when done
  137. virtual void saveGame(COSer<CSaveFile> &h, const int version) override; //saving
  138. virtual void loadGame(CISer<CLoadFile> &h, const int version) override; //loading
  139. virtual void finish() override;
  140. virtual void availableCreaturesChanged(const CGDwelling *town) override;
  141. virtual void heroMoved(const TryMoveHero & details) override;
  142. virtual void stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute) override;
  143. virtual void heroInGarrisonChange(const CGTownInstance *town) override;
  144. virtual void centerView(int3 pos, int focusTime) override;
  145. virtual void tileHidden(const std::unordered_set<int3, ShashInt3> &pos) override;
  146. virtual void artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) override;
  147. virtual void artifactAssembled(const ArtifactLocation &al) override;
  148. virtual void showTavernWindow(const CGObjectInstance *townOrTavern) override;
  149. virtual void showThievesGuildWindow (const CGObjectInstance * obj) override;
  150. virtual void playerBlocked(int reason, bool start) override;
  151. virtual void showPuzzleMap() override;
  152. virtual void showShipyardDialog(const IShipyard *obj) override;
  153. virtual void gameOver(PlayerColor player, bool victory) override;
  154. virtual void artifactPut(const ArtifactLocation &al) override;
  155. virtual void artifactRemoved(const ArtifactLocation &al) override;
  156. virtual void stacksErased(const StackLocation &location) override;
  157. virtual void artifactDisassembled(const ArtifactLocation &al) override;
  158. virtual void heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start) override;
  159. virtual void availableArtifactsChanged(const CGBlackMarket *bm = nullptr) override;
  160. virtual void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town) override;
  161. virtual void tileRevealed(const std::unordered_set<int3, ShashInt3> &pos) override;
  162. virtual void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  163. virtual void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  164. virtual void showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level) override;
  165. virtual void heroMovePointsChanged(const CGHeroInstance * hero) override;
  166. virtual void stackChangedType(const StackLocation &location, const CCreature &newType) override;
  167. virtual void stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count) override;
  168. virtual void newObject(const CGObjectInstance * obj) override;
  169. virtual void showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor) override;
  170. virtual void playerBonusChanged(const Bonus &bonus, bool gain) override;
  171. virtual void newStackInserted(const StackLocation &location, const CStackInstance &stack) override;
  172. virtual void heroCreated(const CGHeroInstance*) override;
  173. virtual void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  174. virtual void showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID) override;
  175. virtual void requestRealized(PackageApplied *pa) override;
  176. virtual void receivedResource(int type, int val) override;
  177. virtual void stacksSwapped(const StackLocation &loc1, const StackLocation &loc2) override;
  178. virtual void objectRemoved(const CGObjectInstance *obj) override;
  179. virtual void showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor) override;
  180. virtual void heroManaPointsChanged(const CGHeroInstance * hero) override;
  181. virtual void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  182. virtual void battleResultsApplied() override;
  183. virtual void objectPropertyChanged(const SetObjectProperty * sop) override;
  184. virtual void buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) override;
  185. virtual void heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain) override;
  186. virtual void showMarketWindow(const IMarket *market, const CGHeroInstance *visitor) override;
  187. virtual void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override;
  188. virtual void battleEnd(const BattleResult *br) override;
  189. void makeTurn();
  190. void makeTurnInternal();
  191. void performTypicalActions();
  192. void buildArmyIn(const CGTownInstance * t);
  193. void striveToGoal(const Goals::CGoal & ultimateGoal);
  194. void endTurn();
  195. void wander(HeroPtr h);
  196. void setGoal(HeroPtr h, const Goals::CGoal goal);
  197. void setGoal(HeroPtr h, Goals::EGoals goalType = Goals::INVALID);
  198. void completeGoal (const Goals::CGoal goal); //safely removes goal from reserved hero
  199. void striveToQuest (const QuestInfo &q);
  200. bool fulfillsGoal (Goals::CGoal &goal, Goals::CGoal &mainGoal);
  201. bool fulfillsGoal (Goals::CGoal &goal, const Goals::CGoal &mainGoal); //TODO: something smarter
  202. void recruitHero(const CGTownInstance * t, bool throwing = false);
  203. std::vector<const CGObjectInstance *> getPossibleDestinations(HeroPtr h);
  204. void buildStructure(const CGTownInstance * t);
  205. //void recruitCreatures(const CGTownInstance * t);
  206. void recruitCreatures(const CGDwelling * d);
  207. bool canGetArmy (const CGHeroInstance * h, const CGHeroInstance * source); //can we get any better stacks from other hero?
  208. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  209. void moveCreaturesToHero(const CGTownInstance * t);
  210. bool goVisitObj(const CGObjectInstance * obj, HeroPtr h);
  211. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  212. bool moveHeroToTile(int3 dst, HeroPtr h);
  213. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  214. void waitTillFree();
  215. void addVisitableObj(const CGObjectInstance *obj);
  216. void markObjectVisited (const CGObjectInstance *obj);
  217. void reserveObject (HeroPtr h, const CGObjectInstance *obj);
  218. //void removeVisitableObj(const CGObjectInstance *obj);
  219. void validateObject(const CGObjectInstance *obj); //checks if object is still visible and if not, removes references to it
  220. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  221. void validateVisitableObjs();
  222. void retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned = false) const;
  223. std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  224. const CGObjectInstance *lookForArt(int aid) const;
  225. bool isAccessible(const int3 &pos);
  226. HeroPtr getHeroWithGrail() const;
  227. const CGObjectInstance *getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate);
  228. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  229. const CGTownInstance *findTownWithTavern() const;
  230. std::vector<HeroPtr> getUnblockedHeroes() const;
  231. HeroPtr primaryHero() const;
  232. TResources freeResources() const; //owned resources minus gold reserve
  233. TResources estimateIncome() const;
  234. bool containsSavedRes(const TResources &cost) const;
  235. void checkHeroArmy (HeroPtr h);
  236. void requestSent(const CPackForServer *pack, int requestID) override;
  237. void answerQuery(QueryID queryID, int selection);
  238. //special function that can be called ONLY from game events handling thread and will send request ASAP
  239. void requestActionASAP(std::function<void()> whatToDo);
  240. template <typename Handler> void serializeInternal(Handler &h, const int version)
  241. {
  242. h & knownSubterraneanGates & townVisitsThisWeek & lockedHeroes & reservedHeroesMap;
  243. h & visitableObjs & alreadyVisited & reservedObjs;
  244. h & saving & status & battlename;
  245. //myCB is restored after load by init call
  246. }
  247. };
  248. class cannotFulfillGoalException : public std::exception
  249. {
  250. std::string msg;
  251. public:
  252. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  253. {
  254. }
  255. virtual ~cannotFulfillGoalException() throw ()
  256. {
  257. };
  258. const char *what() const throw () override
  259. {
  260. return msg.c_str();
  261. }
  262. };
  263. class goalFulfilledException : public std::exception
  264. {
  265. public:
  266. Goals::CGoal goal;
  267. explicit goalFulfilledException(Goals::CGoal Goal) : goal(Goal)
  268. {
  269. }
  270. virtual ~goalFulfilledException() throw ()
  271. {
  272. };
  273. const char *what() const throw () override
  274. {
  275. return goal.name().c_str();
  276. }
  277. };
  278. void makePossibleUpgrades(const CArmedInstance *obj);