VCAI.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. #include "Engine/Nullkiller.h"
  26. struct QuestInfo;
  27. class AIStatus
  28. {
  29. boost::mutex mx;
  30. boost::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. template<typename Handler> void serialize(Handler & h, const int version)
  57. {
  58. h & battle;
  59. h & remainingQueries;
  60. h & requestToQueryID;
  61. h & havingTurn;
  62. }
  63. };
  64. class DLL_EXPORT VCAI : public CAdventureAI
  65. {
  66. public:
  67. ObjectInstanceID destinationTeleport;
  68. int3 destinationTeleportPos;
  69. std::vector<ObjectInstanceID> teleportChannelProbingList; //list of teleport channel exits that not visible and need to be (re-)explored
  70. //std::vector<const CGObjectInstance *> visitedThisWeek; //only OPWs
  71. std::set<HeroPtr> invalidPathHeroes; //FIXME, just a workaround
  72. std::map<HeroPtr, Goals::TSubgoal> lockedHeroes; //TODO: allow non-elementar objectives
  73. std::map<HeroPtr, std::set<const CGObjectInstance *>> reservedHeroesMap; //objects reserved by specific heroes
  74. std::set<HeroPtr> heroesUnableToExplore; //these heroes will not be polled for exploration in current state of game
  75. //sets are faster to search, also do not contain duplicates
  76. std::set<const CGObjectInstance *> reservedObjs; //to be visited by specific hero
  77. std::map<HeroPtr, std::set<HeroPtr>> visitedHeroes; //visited this turn //FIXME: this is just bug workaround
  78. AIStatus status;
  79. std::string battlename;
  80. std::shared_ptr<CCallback> myCb;
  81. std::unique_ptr<boost::thread> makingTurn;
  82. private:
  83. boost::mutex turnInterruptionMutex;
  84. public:
  85. ObjectInstanceID selectedObject;
  86. std::unique_ptr<Nullkiller> nullkiller;
  87. VCAI();
  88. virtual ~VCAI();
  89. //TODO: use only smart pointers?
  90. void tryRealize(Goals::DigAtTile & g);
  91. void tryRealize(Goals::Trade & g);
  92. bool isTileNotReserved(const CGHeroInstance * h, int3 t) const; //the tile is not occupied by allied hero and the object is not reserved
  93. std::string getBattleAIName() const override;
  94. void init(std::shared_ptr<CCallback> CB) override;
  95. void yourTurn() override;
  96. 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
  97. void commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID) override; //TODO
  98. 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.
  99. 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
  100. void showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID) override;
  101. void showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects) override;
  102. void saveGame(BinarySerializer & h, const int version) override; //saving
  103. void loadGame(BinaryDeserializer & h, const int version) override; //loading
  104. void finish() override;
  105. void availableCreaturesChanged(const CGDwelling * town) override;
  106. void heroMoved(const TryMoveHero & details) override;
  107. void heroInGarrisonChange(const CGTownInstance * town) override;
  108. void centerView(int3 pos, int focusTime) override;
  109. void tileHidden(const std::unordered_set<int3, ShashInt3> & pos) override;
  110. void artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst) override;
  111. void artifactAssembled(const ArtifactLocation & al) override;
  112. void showTavernWindow(const CGObjectInstance * townOrTavern) override;
  113. void showThievesGuildWindow(const CGObjectInstance * obj) override;
  114. void playerBlocked(int reason, bool start) override;
  115. void showPuzzleMap() override;
  116. void showShipyardDialog(const IShipyard * obj) override;
  117. void gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult) override;
  118. void artifactPut(const ArtifactLocation & al) override;
  119. void artifactRemoved(const ArtifactLocation & al) override;
  120. void artifactDisassembled(const ArtifactLocation & al) override;
  121. void heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start) override;
  122. void availableArtifactsChanged(const CGBlackMarket * bm = nullptr) override;
  123. void heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town) override;
  124. void tileRevealed(const std::unordered_set<int3, ShashInt3> & pos) override;
  125. void heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query) override;
  126. void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val) override;
  127. void showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level) override;
  128. void heroMovePointsChanged(const CGHeroInstance * hero) override;
  129. void garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2) override;
  130. void newObject(const CGObjectInstance * obj) override;
  131. void showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor) override;
  132. void playerBonusChanged(const Bonus & bonus, bool gain) override;
  133. void heroCreated(const CGHeroInstance *) override;
  134. void advmapSpellCast(const CGHeroInstance * caster, int spellID) override;
  135. void showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID) override;
  136. void requestRealized(PackageApplied * pa) override;
  137. void receivedResource() override;
  138. void objectRemoved(const CGObjectInstance * obj) override;
  139. void showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  140. void heroManaPointsChanged(const CGHeroInstance * hero) override;
  141. void heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val) override;
  142. void battleResultsApplied() override;
  143. void objectPropertyChanged(const SetObjectProperty * sop) override;
  144. void buildChanged(const CGTownInstance * town, BuildingID buildingID, int what) override;
  145. void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
  146. void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
  147. void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions) override;
  148. void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
  149. void battleEnd(const BattleResult * br) override;
  150. void makeTurn();
  151. void buildArmyIn(const CGTownInstance * t);
  152. void endTurn();
  153. void recruitHero(const CGTownInstance * t, bool throwing = false);
  154. //void recruitCreatures(const CGTownInstance * t);
  155. void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);
  156. void pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source); //called when we can't find a slot for new stack
  157. void pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other = nullptr);
  158. void moveCreaturesToHero(const CGTownInstance * t);
  159. void performObjectInteraction(const CGObjectInstance * obj, HeroPtr h);
  160. bool makePossibleUpgrades(const CArmedInstance * obj);
  161. bool moveHeroToTile(int3 dst, HeroPtr h);
  162. void buildStructure(const CGTownInstance * t, BuildingID building); //TODO: move to BuildingManager
  163. void lostHero(HeroPtr h); //should remove all references to hero (assigned tasks and so on)
  164. void waitTillFree();
  165. void addVisitableObj(const CGObjectInstance * obj);
  166. void markHeroUnableToExplore(HeroPtr h);
  167. void markHeroAbleToExplore(HeroPtr h);
  168. bool isAbleToExplore(HeroPtr h);
  169. void clearPathsInfo();
  170. void validateObject(const CGObjectInstance * obj); //checks if object is still visible and if not, removes references to it
  171. void validateObject(ObjectIdRef obj); //checks if object is still visible and if not, removes references to it
  172. void retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned = false) const;
  173. void retrieveVisitableObjs();
  174. virtual std::vector<const CGObjectInstance *> getFlaggedObjects() const;
  175. HeroPtr getHeroWithGrail() const;
  176. const CGTownInstance * findTownWithTavern() const;
  177. bool canRecruitAnyHero(const CGTownInstance * t = NULL) const;
  178. void requestSent(const CPackForServer * pack, int requestID) override;
  179. void answerQuery(QueryID queryID, int selection);
  180. //special function that can be called ONLY from game events handling thread and will send request ASAP
  181. void requestActionASAP(std::function<void()> whatToDo);
  182. #if 0
  183. //disabled due to issue 2890
  184. template<typename Handler> void registerGoals(Handler & h)
  185. {
  186. //h.template registerType<Goals::AbstractGoal, Goals::BoostHero>();
  187. h.template registerType<Goals::AbstractGoal, Goals::Build>();
  188. h.template registerType<Goals::AbstractGoal, Goals::BuildThis>();
  189. //h.template registerType<Goals::AbstractGoal, Goals::CIssueCommand>();
  190. h.template registerType<Goals::AbstractGoal, Goals::ClearWayTo>();
  191. h.template registerType<Goals::AbstractGoal, Goals::CollectRes>();
  192. h.template registerType<Goals::AbstractGoal, Goals::Conquer>();
  193. h.template registerType<Goals::AbstractGoal, Goals::DigAtTile>();
  194. h.template registerType<Goals::AbstractGoal, Goals::Explore>();
  195. h.template registerType<Goals::AbstractGoal, Goals::FindObj>();
  196. h.template registerType<Goals::AbstractGoal, Goals::GatherArmy>();
  197. h.template registerType<Goals::AbstractGoal, Goals::GatherTroops>();
  198. h.template registerType<Goals::AbstractGoal, Goals::GetArtOfType>();
  199. h.template registerType<Goals::AbstractGoal, Goals::VisitObj>();
  200. h.template registerType<Goals::AbstractGoal, Goals::Invalid>();
  201. //h.template registerType<Goals::AbstractGoal, Goals::NotLose>();
  202. h.template registerType<Goals::AbstractGoal, Goals::RecruitHero>();
  203. h.template registerType<Goals::AbstractGoal, Goals::VisitHero>();
  204. h.template registerType<Goals::AbstractGoal, Goals::VisitTile>();
  205. h.template registerType<Goals::AbstractGoal, Goals::Win>();
  206. }
  207. #endif
  208. template<typename Handler> void serializeInternal(Handler & h, const int version)
  209. {
  210. std::map<HeroPtr, std::set<const CGTownInstance *>> ignore;
  211. h & nullkiller->memory->knownTeleportChannels;
  212. h & nullkiller->memory->knownSubterraneanGates;
  213. h & destinationTeleport;
  214. h & ignore;
  215. #if 0
  216. //disabled due to issue 2890
  217. h & lockedHeroes;
  218. #else
  219. {
  220. ui32 length = 0;
  221. h & length;
  222. if(!h.saving)
  223. {
  224. std::set<ui32> loadedPointers;
  225. lockedHeroes.clear();
  226. for(ui32 index = 0; index < length; index++)
  227. {
  228. HeroPtr ignored1;
  229. h & ignored1;
  230. ui8 flag = 0;
  231. h & flag;
  232. if(flag)
  233. {
  234. ui32 pid = 0xffffffff;
  235. h & pid;
  236. if(!vstd::contains(loadedPointers, pid))
  237. {
  238. loadedPointers.insert(pid);
  239. ui16 typeId = 0;
  240. //this is the problem requires such hack
  241. //we have to explicitly ignore invalid goal class type id
  242. h & typeId;
  243. Goals::AbstractGoal ignored2;
  244. ignored2.serialize(h, version);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. #endif
  251. h & reservedHeroesMap; //FIXME: cannot instantiate abstract class
  252. h & nullkiller->memory->visitableObjs;
  253. h & nullkiller->memory->alreadyVisited;
  254. h & reservedObjs;
  255. if (version < 788 && !h.saving)
  256. {
  257. TResources saving;
  258. h & saving; //mind the ambiguity
  259. }
  260. h & status;
  261. h & battlename;
  262. h & heroesUnableToExplore;
  263. //myCB is restored after load by init call
  264. }
  265. };