AIUtility.cpp 11 KB

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