VCAI.h 17 KB

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