AIUtility.cpp 11 KB

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