VCAI.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. * VCAI.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "AIUtility.h"
  12. #include "Goals/AbstractGoal.h"
  13. #include "../../lib/ConditionalWait.h"
  14. #include "../../lib/GameConstants.h"
  15. #include "../../lib/GameLibrary.h"
  16. #include "../../lib/CCreatureHandler.h"
  17. #include "../../lib/callback/CAdventureAI.h"
  18. #include "../../lib/mapObjects/MiscObjects.h"
  19. #include "../../lib/spells/CSpellHandler.h"
  20. #include "Pathfinding/AIPathfinder.h"
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. struct QuestInfo;
  23. class PathfinderCache;
  24. class AsyncRunner;
  25. VCMI_LIB_NAMESPACE_END
  26. class AIhelper;
  27. class AIStatus
  28. {
  29. std::mutex mx;
  30. std::condition_variable cv;
  31. BattleState battle;
  32. std::map<QueryID, std::string> remainingQueries;
  33. 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)
  34. std::vector<const CGObjectInstance *> objectsBeingVisited;
  35. bool ongoingHeroMovement;
  36. bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
  37. bool havingTurn;
  38. public:
  39. AIStatus();
  40. ~AIStatus();
  41. void setBattle(BattleState BS);
  42. void setMove(bool ongoing);
  43. void setChannelProbing(bool ongoing);
  44. bool channelProbing();
  45. BattleState getBattle();
  46. void addQuery(QueryID ID, std::string description);
  47. void removeQuery(QueryID ID);
  48. int getQueriesCount();
  49. void startedTurn();
  50. void madeTurn();
  51. void waitTillFree();
  52. bool haveTurn();
  53. void attemptedAnsweringQuery(QueryID queryID, int answerRequestID);
  54. void receivedAnswerConfirmation(int answerRequestID, int result);
  55. void heroVisit(const CGObjectInstance * obj, bool started);
  56. };
  57. class DLL_EXPORT VCAI : public CAdventureAI
  58. {
  59. public:
  60. friend class FuzzyHelper;
  61. friend class ResourceManager;
  62. friend class BuildingManager;
  63. std::map<TeleportChannelID, std::shared_ptr<TeleportChannel>> knownTeleportChannels;
  64. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  65. ObjectInstanceID destinationTeleport;
  66. int3 destinationTeleportPos;
  67. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  68. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  69. std::map<HeroPtr, std::set<const CGTownInstance *>> townVisitsThisWeek;
  70. std::unique_ptr<PathfinderCache> pathfinderCache;
  71. //part of mainLoop, but accessible from outside
  72. std::vector<Goals::TSubgoal> basicGoals;
  73. Goals::TGoalVec goalsToRemove;
  74. Goals::TGoalVec goalsToAdd;
  75. std::map<Goals::TSubgoal, Goals::TGoalVec> ultimateGoalsFromBasic; //theoreticlaly same goal can fulfill multiple basic goals
  76. std::set<HeroPtr> invalidPathHeroes; //FIXME, just a workaround
  77. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  78. std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  79. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  80. //sets are faster to search, also do not contain duplicates
  81. std::set<const CGObjectInstance *> visitableObjs;
  82. std::set<const CGObjectInstance *> alreadyVisited;
  83. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  84. std::map<HeroPtr, std::set<HeroPtr>> visitedHeroes; //visited this turn //FIXME: this is just bug workaround
  85. AIStatus status;
  86. std::string battlename;
  87. std::shared_ptr<CCallback> myCb;
  88. std::unique_ptr<AsyncRunner> asyncTasks;
  89. ThreadInterruption makingTurnInterrupption;
  90. public:
  91. ObjectInstanceID selectedObject;
  92. AIhelper * ah;
  93. VCAI();
  94. virtual ~VCAI();
  95. //TODO: use only smart pointers?
  96. void tryRealize(Goals::Explore & g);
  97. void tryRealize(Goals::RecruitHero & g);
  98. void tryRealize(Goals::VisitTile & g);
  99. void tryRealize(Goals::VisitObj & g);
  100. void tryRealize(Goals::VisitHero & g);
  101. void tryRealize(Goals::BuildThis & g);
  102. void tryRealize(Goals::DigAtTile & g);
  103. void tryRealize(Goals::Trade & g);
  104. void tryRealize(Goals::BuyArmy & g);
  105. void tryRealize(Goals::Invalid & g);
  106. void tryRealize(Goals::AbstractGoal & g);
  107. bool isTileNotReserved(const CGHeroInstance * h, int3 t) const; //the tile is not occupied by allied hero and the object is not reserved
  108. std::string getBattleAIName() const override;
  109. void initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB) override;
  110. void yourTurn(QueryID queryID) override;
  111. void heroGotLevel(const CGHeroInstance * hero, 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
  112. void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  113. void showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept) 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.
  114. 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
  115. void showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  116. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  117. void finish() override;
  118. void availableCreaturesChanged(const CGDwelling * town) override;
  119. void heroMoved(const TryMoveHero & details, bool verbose = true) override;
  120. void heroInGarrisonChange(const CGTownInstance * town) override;
  121. void centerView(int3 pos, int focusTime) override;
  122. void tileHidden(const FowTilesType & pos) override;
  123. void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  124. void artifactAssembled(const ArtifactLocation & al) override;
  125. void showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID) override;
  126. void showThievesGuildWindow(const CGObjectInstance * obj) override;
  127. void playerBlocked(int reason, bool start) override;
  128. void showPuzzleMap() override;
  129. void showShipyardDialog(const IShipyard * obj) override;
  130. void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  131. void artifactPut(const ArtifactLocation & al) override;
  132. void artifactRemoved(const ArtifactLocation & al) override;
  133. void artifactDisassembled(const ArtifactLocation & al) override;
  134. void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  135. void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  136. void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  137. void tileRevealed(const FowTilesType & pos) override;
  138. void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  139. void heroExperienceChanged(const CGHeroInstance * hero, si64 val) override;
  140. void heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val) override;
  141. void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID) override;
  142. void heroMovePointsChanged(const CGHeroInstance * hero) override;
  143. void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  144. void newObject(const CGObjectInstance * obj) override;
  145. void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  146. void playerBonusChanged(const Bonus & bonus, bool gain) override;
  147. void heroCreated(const CGHeroInstance *) override;
  148. void advmapSpellCast(const CGHeroInstance * caster, SpellID spellID) override;
  149. void showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID) override;
  150. void requestRealized(PackageApplied * pa) override;
  151. void receivedResource() override;
  152. void objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator) override;
  153. void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID) override;
  154. void heroManaPointsChanged(const CGHeroInstance * hero) override;
  155. void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  156. void battleResultsApplied() override;
  157. void beforeObjectPropertyChanged(const SetObjectProperty * sop) override;
  158. void objectPropertyChanged(const SetObjectProperty * sop) override;
  159. void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  160. void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  161. void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID) override;
  162. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain) override;
  163. void battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed) override;
  164. void battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID) override;
  165. std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState) override;
  166. void makeTurn();
  167. void mainLoop();
  168. void performTypicalActions();
  169. void buildArmyIn(const CGTownInstance * t);
  170. void striveToGoal(Goals::TSubgoal ultimateGoal);
  171. Goals::TSubgoal decomposeGoal(Goals::TSubgoal ultimateGoal);
  172. void endTurn();
  173. void wander(HeroPtr h);
  174. void setGoal(HeroPtr h, Goals::TSubgoal goal);
  175. void evaluateGoal(HeroPtr h); //evaluates goal assigned to hero, if any
  176. void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero
  177. void recruitHero(const CGTownInstance * t, bool throwing = false);
  178. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit = std::nullopt);
  179. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const;
  180. //void recruitCreatures(const CGTownInstance * t);
  181. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  182. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  183. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  184. void moveCreaturesToHero(const CGTownInstance * t);
  185. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  186. bool moveHeroToTile(int3 dst, HeroPtr h);
  187. void buildStructure(const CGTownInstance * t, BuildingID building); //TODO: move to BuildingManager
  188. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  189. void waitTillFree();
  190. void addVisitableObj(const CGObjectInstance * obj);
  191. void markObjectVisited(const CGObjectInstance * obj);
  192. void reserveObject(HeroPtr h, const CGObjectInstance * obj); //TODO: reserve all objects that heroes attempt to visit
  193. void unreserveObject(HeroPtr h, const CGObjectInstance * obj);
  194. void markHeroUnableToExplore(HeroPtr h);
  195. void markHeroAbleToExplore(HeroPtr h);
  196. bool isAbleToExplore(HeroPtr h);
  197. void clearPathsInfo();
  198. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  199. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  200. void validateVisitableObjs();
  201. void retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
  202. void retrieveVisitableObjs();
  203. virtual std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  204. const CGObjectInstance * lookForArt(ArtifactID aid) const;
  205. bool isAccessible(const int3 & pos) const;
  206. HeroPtr getHeroWithGrail() const;
  207. const CGObjectInstance * getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate);
  208. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  209. //optimization - use one SM for every hero call
  210. const CGTownInstance * findTownWithTavern() const;
  211. bool canRecruitAnyHero(const CGTownInstance * t = nullptr) const;
  212. Goals::TSubgoal getGoal(HeroPtr h) const;
  213. bool canAct(HeroPtr h) const;
  214. std::vector<HeroPtr> getUnblockedHeroes() const;
  215. std::vector<HeroPtr> getMyHeroes() const;
  216. HeroPtr primaryHero() const;
  217. void checkHeroArmy(HeroPtr h);
  218. std::shared_ptr<const CPathsInfo> getPathsInfo(const CGHeroInstance * h) const;
  219. void invalidatePaths() override;
  220. void requestSent(const CPackForServer * pack, int requestID) override;
  221. void answerQuery(QueryID queryID, int selection);
  222. //special function that can be called ONLY from game events handling thread and will send request ASAP
  223. void executeActionAsync(const std::string & description, const std::function<void()> & whatToDo);
  224. };
  225. class cannotFulfillGoalException : public std::exception
  226. {
  227. std::string msg;
  228. public:
  229. explicit cannotFulfillGoalException(crstring _Message)
  230. : msg(_Message)
  231. {
  232. }
  233. const char * what() const noexcept override
  234. {
  235. return msg.c_str();
  236. }
  237. };
  238. class goalFulfilledException : public std::exception
  239. {
  240. std::string msg;
  241. public:
  242. Goals::TSubgoal goal;
  243. explicit goalFulfilledException(Goals::TSubgoal Goal)
  244. : goal(Goal)
  245. {
  246. msg = goal->name();
  247. }
  248. const char * what() const noexcept override
  249. {
  250. return msg.c_str();
  251. }
  252. };
  253. void makePossibleUpgrades(const CArmedInstance * obj);