VCAI.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/AI_Base.h"
  14. #include "../../CCallback.h"
  15. #include "../../lib/CThreadHelper.h"
  16. #include "../../lib/GameConstants.h"
  17. #include "../../lib/VCMI_Lib.h"
  18. #include "../../lib/CBuildingHandler.h"
  19. #include "../../lib/CCreatureHandler.h"
  20. #include "../../lib/CTownHandler.h"
  21. #include "../../lib/mapObjects/MiscObjects.h"
  22. #include "../../lib/spells/CSpellHandler.h"
  23. #include "../../lib/CondSh.h"
  24. #include "Pathfinding/AIPathfinder.h"
  25. struct QuestInfo;
  26. class AIhelper;
  27. class Nullkiller;
  28. class AIStatus
  29. {
  30. boost::mutex mx;
  31. boost::condition_variable cv;
  32. BattleState battle;
  33. std::map<QueryID, std::string> remainingQueries;
  34. 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)
  35. std::vector<const CGObjectInstance *> objectsBeingVisited;
  36. bool ongoingHeroMovement;
  37. bool ongoingChannelProbing; // true if AI currently explore bidirectional teleport channel exits
  38. bool havingTurn;
  39. public:
  40. AIStatus();
  41. ~AIStatus();
  42. void setBattle(BattleState BS);
  43. void setMove(bool ongoing);
  44. void setChannelProbing(bool ongoing);
  45. bool channelProbing();
  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;
  60. h & remainingQueries;
  61. h & requestToQueryID;
  62. h & havingTurn;
  63. }
  64. };
  65. class DLL_EXPORT VCAI : public CAdventureAI
  66. {
  67. public:
  68. friend class FuzzyHelper;
  69. friend class ResourceManager;
  70. friend class BuildingManager;
  71. std::map<TeleportChannelID, std::shared_ptr<TeleportChannel>> knownTeleportChannels;
  72. std::map<const CGObjectInstance *, const CGObjectInstance *> knownSubterraneanGates;
  73. ObjectInstanceID destinationTeleport;
  74. int3 destinationTeleportPos;
  75. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  76. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  77. std::map<HeroPtr, std::set<const CGTownInstance *>> townVisitsThisWeek;
  78. std::set<HeroPtr> invalidPathHeroes; //FIXME, just a workaround
  79. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  80. std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  81. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  82. //sets are faster to search, also do not contain duplicates
  83. std::set<const CGObjectInstance *> visitableObjs;
  84. std::set<const CGObjectInstance *> alreadyVisited;
  85. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  86. std::map<HeroPtr, std::set<HeroPtr>> visitedHeroes; //visited this turn //FIXME: this is just bug workaround
  87. AIStatus status;
  88. std::string battlename;
  89. std::shared_ptr<CCallback> myCb;
  90. std::unique_ptr<boost::thread> makingTurn;
  91. private:
  92. boost::mutex turnInterruptionMutex;
  93. public:
  94. ObjectInstanceID selectedObject;
  95. AIhelper * ah;
  96. std::unique_ptr<Nullkiller> nullkiller;
  97. VCAI();
  98. virtual ~VCAI();
  99. //TODO: use only smart pointers?
  100. void tryRealize(Goals::Explore & g);
  101. void tryRealize(Goals::RecruitHero & g);
  102. void tryRealize(Goals::VisitTile & g);
  103. void tryRealize(Goals::VisitObj & g);
  104. void tryRealize(Goals::VisitHero & g);
  105. void tryRealize(Goals::BuildThis & g);
  106. void tryRealize(Goals::DigAtTile & g);
  107. void tryRealize(Goals::Trade & g);
  108. void tryRealize(Goals::BuyArmy & g);
  109. void tryRealize(Goals::Invalid & g);
  110. void tryRealize(Goals::AbstractGoal & g);
  111. bool isTileNotReserved(const CGHeroInstance * h, int3 t) const; //the tile is not occupied by allied hero and the object is not reserved
  112. std::string getBattleAIName() const override;
  113. void init(std::shared_ptr<CCallback> CB) override;
  114. void yourTurn() override;
  115. 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
  116. void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  117. 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.
  118. 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
  119. void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  120. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  121. void saveGame(BinarySerializer & h, const int version) override; //saving
  122. void loadGame(BinaryDeserializer & h, const int version) override; //loading
  123. void finish() override;
  124. void availableCreaturesChanged(const CGDwelling * town) override;
  125. void heroMoved(const TryMoveHero & details) override;
  126. void heroInGarrisonChange(const CGTownInstance * town) override;
  127. void centerView(int3 pos, int focusTime) override;
  128. void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override;
  129. void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  130. void artifactAssembled(const ArtifactLocation & al) override;
  131. void showTavernWindow(const CGObjectInstance * townOrTavern) override;
  132. void showThievesGuildWindow(const CGObjectInstance * obj) override;
  133. void playerBlocked(int reason, bool start) override;
  134. void showPuzzleMap() override;
  135. void showShipyardDialog(const IShipyard * obj) override;
  136. void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  137. void artifactPut(const ArtifactLocation & al) override;
  138. void artifactRemoved(const ArtifactLocation & al) override;
  139. void artifactDisassembled(const ArtifactLocation & al) override;
  140. void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  141. void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  142. void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  143. void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override;
  144. void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  145. void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  146. void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
  147. void heroMovePointsChanged(const CGHeroInstance * hero) override;
  148. void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  149. void newObject(const CGObjectInstance * obj) override;
  150. void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  151. void playerBonusChanged(const Bonus & bonus, bool gain) override;
  152. void heroCreated(const CGHeroInstance *) override;
  153. void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  154. void showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID) override;
  155. void requestRealized(PackageApplied * pa) override;
  156. void receivedResource() override;
  157. void objectRemoved(const CGObjectInstance * obj) override;
  158. void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  159. void heroManaPointsChanged(const CGHeroInstance * hero) override;
  160. void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  161. void battleResultsApplied() override;
  162. void objectPropertyChanged(const SetObjectProperty * sop) override;
  163. void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  164. void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  165. void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  166. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
  167. void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
  168. void battleEnd(const BattleResult * br) override;
  169. void makeTurn();
  170. void buildArmyIn(const CGTownInstance * t);
  171. void endTurn();
  172. void recruitHero(const CGTownInstance * t, bool throwing = false);
  173. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<float> movementCostLimit = boost::none);
  174. bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const;
  175. //void recruitCreatures(const CGTownInstance * t);
  176. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  177. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  178. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  179. void moveCreaturesToHero(const CGTownInstance * t);
  180. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  181. bool makePossibleUpgrades(const CArmedInstance * obj);
  182. bool moveHeroToTile(int3 dst, HeroPtr h);
  183. void buildStructure(const CGTownInstance * t, BuildingID building); //TODO: move to BuildingManager
  184. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  185. void waitTillFree();
  186. void addVisitableObj(const CGObjectInstance * obj);
  187. void markObjectVisited(const CGObjectInstance * obj);
  188. void markHeroUnableToExplore(HeroPtr h);
  189. void markHeroAbleToExplore(HeroPtr h);
  190. bool isAbleToExplore(HeroPtr h);
  191. void clearPathsInfo();
  192. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  193. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  194. void validateVisitableObjs();
  195. void retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
  196. void retrieveVisitableObjs();
  197. virtual std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  198. const CGObjectInstance * lookForArt(int aid) const;
  199. bool isAccessible(const int3 & pos) const;
  200. HeroPtr getHeroWithGrail() const;
  201. const CGObjectInstance * getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate);
  202. bool isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies = false) const;
  203. //optimization - use one SM for every hero call
  204. const CGTownInstance * findTownWithTavern() const;
  205. bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
  206. Goals::TSubgoal getGoal(HeroPtr h) const;
  207. bool canAct(HeroPtr h) const;
  208. std::vector<HeroPtr> getUnblockedHeroes() const;
  209. std::vector<HeroPtr> getMyHeroes() const;
  210. HeroPtr primaryHero() const;
  211. void requestSent(const CPackForServer * pack, int requestID) override;
  212. void answerQuery(QueryID queryID, int selection);
  213. //special function that can be called ONLY from game events handling thread and will send request ASAP
  214. void requestActionASAP(std::function<void()> whatToDo);
  215. #if 0
  216. //disabled due to issue 2890
  217. template<typename Handler> void registerGoals(Handler & h)
  218. {
  219. //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
  220. h.template registerType<Goals::AbstractGoal, Goals::Build>();
  221. h.template registerType<Goals::AbstractGoal, Goals::BuildThis>();
  222. //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>();
  223. h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>();
  224. h.template registerType<Goals::AbstractGoal, Goals::CollectRes>();
  225. h.template registerType<Goals::AbstractGoal, Goals::Conquer>();
  226. h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>();
  227. h.template registerType<Goals::AbstractGoal, Goals::Explore>();
  228. h.template registerType<Goals::AbstractGoal, Goals::FindObj>();
  229. h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>();
  230. h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>();
  231. h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>();
  232. h.template registerType<Goals::AbstractGoal, Goals::VisitObj>();
  233. h.template registerType<Goals::AbstractGoal, Goals::Invalid>();
  234. //h.template registerType<Goals::AbstractGoal, Goals::NotLose>();
  235. h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>();
  236. h.template registerType<Goals::AbstractGoal, Goals::VisitHero>();
  237. h.template registerType<Goals::AbstractGoal, Goals::VisitTile>();
  238. h.template registerType<Goals::AbstractGoal, Goals::Win>();
  239. }
  240. #endif
  241. template<typename Handler> void serializeInternal(Handler & h, const int version)
  242. {
  243. h & knownTeleportChannels;
  244. h & knownSubterraneanGates;
  245. h & destinationTeleport;
  246. h & townVisitsThisWeek;
  247. #if 0
  248. //disabled due to issue 2890
  249. h & lockedHeroes;
  250. #else
  251. {
  252. ui32 length = 0;
  253. h & length;
  254. if(!h.saving)
  255. {
  256. std::set<ui32> loadedPointers;
  257. lockedHeroes.clear();
  258. for(ui32 index = 0; index < length; index++)
  259. {
  260. HeroPtr ignored1;
  261. h & ignored1;
  262. ui8 flag = 0;
  263. h & flag;
  264. if(flag)
  265. {
  266. ui32 pid = 0xffffffff;
  267. h & pid;
  268. if(!vstd::contains(loadedPointers, pid))
  269. {
  270. loadedPointers.insert(pid);
  271. ui16 typeId = 0;
  272. //this is the problem requires such hack
  273. //we have to explicitly ignore invalid goal class type id
  274. h & typeId;
  275. Goals::AbstractGoal ignored2;
  276. ignored2.serialize(h, version);
  277. }
  278. }
  279. }
  280. }
  281. }
  282. #endif
  283. h & reservedHeroesMap; //FIXME: cannot instantiate abstract class
  284. h & visitableObjs;
  285. h & alreadyVisited;
  286. h & reservedObjs;
  287. if (version < 788 && !h.saving)
  288. {
  289. TResources saving;
  290. h & saving; //mind the ambiguity
  291. }
  292. h & status;
  293. h & battlename;
  294. h & heroesUnableToExplore;
  295. //myCB is restored after load by init call
  296. }
  297. };
  298. class cannotFulfillGoalException : public std::exception
  299. {
  300. std::string msg;
  301. public:
  302. explicit cannotFulfillGoalException(crstring _Message)
  303. : msg(_Message)
  304. {
  305. }
  306. virtual ~cannotFulfillGoalException() throw ()
  307. {
  308. };
  309. const char * what() const throw () override
  310. {
  311. return msg.c_str();
  312. }
  313. };
  314. class goalFulfilledException : public std::exception
  315. {
  316. std::string msg;
  317. public:
  318. Goals::TSubgoal goal;
  319. explicit goalFulfilledException(Goals::TSubgoal Goal)
  320. : goal(Goal)
  321. {
  322. msg = goal->name();
  323. }
  324. virtual ~goalFulfilledException() throw ()
  325. {
  326. };
  327. const char * what() const throw () override
  328. {
  329. return msg.c_str();
  330. }
  331. };