AIUtility.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * AIUtility.cpp, 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. #include "StdInc.h"
  11. #include "AIUtility.h"
  12. #include "AIGateway.h"
  13. #include "Goals/Goals.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/CConfigHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/mapping/CMapDefines.h"
  19. #include "../../lib/GameSettings.h"
  20. #include <vcmi/CreatureService.h>
  21. namespace NKAI
  22. {
  23. extern boost::thread_specific_ptr<AIGateway> ai;
  24. //extern static const int3 dirs[8];
  25. const CGObjectInstance * ObjectIdRef::operator->() const
  26. {
  27. return cb->getObj(id, false);
  28. }
  29. ObjectIdRef::operator const CGObjectInstance *() const
  30. {
  31. return cb->getObj(id, false);
  32. }
  33. ObjectIdRef::operator bool() const
  34. {
  35. return cb->getObj(id, false);
  36. }
  37. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  38. : id(_id)
  39. {
  40. }
  41. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  42. : id(obj->id)
  43. {
  44. }
  45. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  46. {
  47. return id < rhs.id;
  48. }
  49. HeroPtr::HeroPtr(const CGHeroInstance * H)
  50. {
  51. if(!H)
  52. {
  53. //init from nullptr should equal to default init
  54. *this = HeroPtr();
  55. return;
  56. }
  57. h = H;
  58. name = h->getNameTranslated();
  59. hid = H->id;
  60. // infosCount[ai->playerID][hid]++;
  61. }
  62. HeroPtr::HeroPtr()
  63. {
  64. h = nullptr;
  65. hid = ObjectInstanceID();
  66. }
  67. HeroPtr::~HeroPtr()
  68. {
  69. // if(hid >= 0)
  70. // infosCount[ai->playerID][hid]--;
  71. }
  72. bool HeroPtr::operator<(const HeroPtr & rhs) const
  73. {
  74. return hid < rhs.hid;
  75. }
  76. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull) const
  77. {
  78. //TODO? check if these all assertions every time we get info about hero affect efficiency
  79. //
  80. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  81. assert(doWeExpectNull || h);
  82. if(h)
  83. {
  84. auto obj = cb->getObj(hid);
  85. //const bool owned = obj && obj->tempOwner == ai->playerID;
  86. if(doWeExpectNull && !obj)
  87. {
  88. return nullptr;
  89. }
  90. else
  91. {
  92. if (!obj)
  93. logAi->error("Accessing no longer accessible hero %s!", h->getNameTranslated());
  94. //assert(obj);
  95. //assert(owned);
  96. }
  97. }
  98. return h;
  99. }
  100. const CGHeroInstance * HeroPtr::get(CCallback * cb, bool doWeExpectNull) const
  101. {
  102. //TODO? check if these all assertions every time we get info about hero affect efficiency
  103. //
  104. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  105. assert(doWeExpectNull || h);
  106. if(h)
  107. {
  108. auto obj = cb->getObj(hid);
  109. //const bool owned = obj && obj->tempOwner == ai->playerID;
  110. if(doWeExpectNull && !obj)
  111. {
  112. return nullptr;
  113. }
  114. else
  115. {
  116. assert(obj);
  117. //assert(owned);
  118. }
  119. }
  120. return h;
  121. }
  122. const CGHeroInstance * HeroPtr::operator->() const
  123. {
  124. return get();
  125. }
  126. bool HeroPtr::validAndSet() const
  127. {
  128. return get(true);
  129. }
  130. const CGHeroInstance * HeroPtr::operator*() const
  131. {
  132. return get();
  133. }
  134. bool HeroPtr::operator==(const HeroPtr & rhs) const
  135. {
  136. return h == rhs.get(true);
  137. }
  138. bool CDistanceSorter::operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs) const
  139. {
  140. const CGPathNode * ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos());
  141. const CGPathNode * rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
  142. return ln->getCost() < rn->getCost();
  143. }
  144. bool isSafeToVisit(HeroPtr h, const CCreatureSet * heroArmy, uint64_t dangerStrength)
  145. {
  146. const ui64 heroStrength = h->getFightingStrength() * heroArmy->getArmyStrength();
  147. if(dangerStrength)
  148. {
  149. return heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength;
  150. }
  151. return true; //there's no danger
  152. }
  153. bool isSafeToVisit(HeroPtr h, uint64_t dangerStrength)
  154. {
  155. return isSafeToVisit(h, h.get(), dangerStrength);
  156. }
  157. bool isObjectRemovable(const CGObjectInstance * obj)
  158. {
  159. //FIXME: move logic to object property!
  160. switch (obj->ID)
  161. {
  162. case Obj::MONSTER:
  163. case Obj::RESOURCE:
  164. case Obj::CAMPFIRE:
  165. case Obj::TREASURE_CHEST:
  166. case Obj::ARTIFACT:
  167. case Obj::BORDERGUARD:
  168. case Obj::FLOTSAM:
  169. case Obj::PANDORAS_BOX:
  170. case Obj::OCEAN_BOTTLE:
  171. case Obj::SEA_CHEST:
  172. case Obj::SHIPWRECK_SURVIVOR:
  173. case Obj::SPELL_SCROLL:
  174. return true;
  175. break;
  176. default:
  177. return false;
  178. break;
  179. }
  180. }
  181. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  182. {
  183. // TODO: Such information should be provided by pathfinder
  184. // Tile must be free or with unoccupied boat
  185. if(!t->blocked)
  186. {
  187. return true;
  188. }
  189. else if(!fromWater) // do not try to board when in water sector
  190. {
  191. if(t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  192. return true;
  193. }
  194. return false;
  195. }
  196. bool isObjectPassable(const Nullkiller * ai, const CGObjectInstance * obj)
  197. {
  198. return isObjectPassable(obj, ai->playerID, ai->cb->getPlayerRelations(obj->tempOwner, ai->playerID));
  199. }
  200. bool isObjectPassable(const CGObjectInstance * obj)
  201. {
  202. return isObjectPassable(obj, ai->playerID, ai->myCb->getPlayerRelations(obj->tempOwner, ai->playerID));
  203. }
  204. // Pathfinder internal helper
  205. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations::PlayerRelations objectRelations)
  206. {
  207. if((obj->ID == Obj::GARRISON || obj->ID == Obj::GARRISON2)
  208. && objectRelations != PlayerRelations::ENEMIES)
  209. return true;
  210. if(obj->ID == Obj::BORDER_GATE)
  211. {
  212. auto quest = dynamic_cast<const CGKeys *>(obj);
  213. if(quest->passableFor(playerColor))
  214. return true;
  215. }
  216. return false;
  217. }
  218. bool isBlockVisitObj(const int3 & pos)
  219. {
  220. if(auto obj = cb->getTopObj(pos))
  221. {
  222. if(obj->blockVisit) //we can't stand on that object
  223. return true;
  224. }
  225. return false;
  226. }
  227. creInfo infoFromDC(const dwellingContent & dc)
  228. {
  229. creInfo ci;
  230. ci.count = dc.first;
  231. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  232. if (ci.creID != -1)
  233. {
  234. ci.cre = VLC->creatures()->getById(ci.creID);
  235. ci.level = ci.cre->getLevel(); //this is creature tier, while tryRealize expects dwelling level. Ignore.
  236. }
  237. else
  238. {
  239. ci.cre = nullptr;
  240. ci.level = 0;
  241. }
  242. return ci;
  243. }
  244. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  245. {
  246. return h1->getTotalStrength() < h2->getTotalStrength();
  247. }
  248. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  249. {
  250. return a1->getArmyStrength() < a2->getArmyStrength();
  251. }
  252. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2)
  253. {
  254. auto art1 = a1->artType;
  255. auto art2 = a2->artType;
  256. if(art1->price == art2->price)
  257. return art1->valOfBonuses(Bonus::PRIMARY_SKILL) > art2->valOfBonuses(Bonus::PRIMARY_SKILL);
  258. else
  259. return art1->price > art2->price;
  260. }
  261. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  262. {
  263. if(!obj)
  264. return false;
  265. //TODO: allow polling of remaining creatures in dwelling
  266. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  267. return rewardable->getResetDuration() == 7;
  268. if(dynamic_cast<const CGDwelling *>(obj))
  269. return true;
  270. if(dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  271. return true;
  272. switch(obj->ID)
  273. {
  274. case Obj::STABLES:
  275. case Obj::MAGIC_WELL:
  276. case Obj::HILL_FORT:
  277. return true;
  278. case Obj::BORDER_GATE:
  279. case Obj::BORDERGUARD:
  280. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  281. }
  282. return false;
  283. }
  284. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  285. {
  286. auto end = std::chrono::high_resolution_clock::now();
  287. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  288. }
  289. // todo: move to obj manager
  290. bool shouldVisit(const Nullkiller * ai, const CGHeroInstance * h, const CGObjectInstance * obj)
  291. {
  292. auto relations = ai->cb->getPlayerRelations(obj->tempOwner, h->tempOwner);
  293. switch(obj->ID)
  294. {
  295. case Obj::TOWN:
  296. case Obj::HERO: //never visit our heroes at random
  297. return relations == PlayerRelations::ENEMIES; //do not visit our towns at random
  298. case Obj::BORDER_GATE:
  299. {
  300. for(auto q : ai->cb->getMyQuests())
  301. {
  302. if(q.obj == obj)
  303. {
  304. return false; // do not visit guards or gates when wandering
  305. }
  306. }
  307. return true; //we don't have this quest yet
  308. }
  309. case Obj::BORDERGUARD: //open borderguard if possible
  310. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  311. case Obj::SEER_HUT:
  312. {
  313. for(auto q : ai->cb->getMyQuests())
  314. {
  315. if(q.obj == obj)
  316. {
  317. if(q.quest->checkQuest(h))
  318. return true; //we completed the quest
  319. else
  320. return false; //we can't complete this quest
  321. }
  322. }
  323. return true; //we don't have this quest yet
  324. }
  325. case Obj::CREATURE_GENERATOR1:
  326. {
  327. if(relations == PlayerRelations::ENEMIES)
  328. return true; //flag just in case
  329. if(relations == PlayerRelations::ALLIES)
  330. return false;
  331. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  332. for(auto level : d->creatures)
  333. {
  334. for(auto c : level.second)
  335. {
  336. if(level.first
  337. && h->getSlotFor(CreatureID(c)) != SlotID()
  338. && ai->cb->getResourceAmount().canAfford(c.toCreature()->getFullRecruitCost()))
  339. {
  340. return true;
  341. }
  342. }
  343. }
  344. return false;
  345. }
  346. case Obj::HILL_FORT:
  347. {
  348. for(auto slot : h->Slots())
  349. {
  350. if(slot.second->type->hasUpgrades())
  351. return true; //TODO: check price?
  352. }
  353. return false;
  354. }
  355. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  356. case Obj::MONOLITH_ONE_WAY_EXIT:
  357. case Obj::MONOLITH_TWO_WAY:
  358. case Obj::WHIRLPOOL:
  359. return false;
  360. case Obj::SCHOOL_OF_MAGIC:
  361. case Obj::SCHOOL_OF_WAR:
  362. {
  363. if(ai->getFreeGold() < 1000)
  364. return false;
  365. break;
  366. }
  367. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  368. if(h->level < 10)
  369. return false;
  370. break;
  371. case Obj::TREE_OF_KNOWLEDGE:
  372. {
  373. if(ai->heroManager->getHeroRole(h) == HeroRole::SCOUT)
  374. return false;
  375. TResources myRes = ai->getFreeResources();
  376. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  377. return false;
  378. break;
  379. }
  380. case Obj::MAGIC_WELL:
  381. return h->mana < h->manaLimit();
  382. case Obj::PRISON:
  383. return ai->cb->getHeroesInfo().size() < VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  384. case Obj::TAVERN:
  385. case Obj::EYE_OF_MAGI:
  386. case Obj::BOAT:
  387. case Obj::SIGN:
  388. return false;
  389. }
  390. if(obj->wasVisited(h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  391. return false;
  392. return true;
  393. }
  394. bool townHasFreeTavern(const CGTownInstance * town)
  395. {
  396. if(!town->hasBuilt(BuildingID::TAVERN)) return false;
  397. if(!town->visitingHero) return true;
  398. bool canMoveVisitingHeroToGarnison = !town->getUpperArmy()->stacksCount();
  399. return canMoveVisitingHeroToGarnison;
  400. }
  401. }