AIUtility.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 "FuzzyHelper.h"
  14. #include "Goals/Goals.h"
  15. #include "../../lib/UnlockGuard.h"
  16. #include "../../lib/CConfigHandler.h"
  17. #include "../../lib/CHeroHandler.h"
  18. #include "../../lib/mapObjects/CBank.h"
  19. #include "../../lib/mapObjects/CGTownInstance.h"
  20. #include "../../lib/mapObjects/CQuest.h"
  21. #include "../../lib/mapping/CMapDefines.h"
  22. extern boost::thread_specific_ptr<CCallback> cb;
  23. extern boost::thread_specific_ptr<VCAI> ai;
  24. extern FuzzyHelper * fh;
  25. //extern static const int3 dirs[8];
  26. const CGObjectInstance * ObjectIdRef::operator->() const
  27. {
  28. return cb->getObj(id, false);
  29. }
  30. ObjectIdRef::operator const CGObjectInstance *() const
  31. {
  32. return cb->getObj(id, false);
  33. }
  34. ObjectIdRef::operator bool() const
  35. {
  36. return cb->getObj(id, false);
  37. }
  38. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  39. : id(_id)
  40. {
  41. }
  42. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  43. : id(obj->id)
  44. {
  45. }
  46. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  47. {
  48. return id < rhs.id;
  49. }
  50. HeroPtr::HeroPtr(const CGHeroInstance * H)
  51. {
  52. if(!H)
  53. {
  54. //init from nullptr should equal to default init
  55. *this = HeroPtr();
  56. return;
  57. }
  58. h = H;
  59. name = h->name;
  60. hid = H->id;
  61. // infosCount[ai->playerID][hid]++;
  62. }
  63. HeroPtr::HeroPtr()
  64. {
  65. h = nullptr;
  66. hid = ObjectInstanceID();
  67. }
  68. HeroPtr::~HeroPtr()
  69. {
  70. // if(hid >= 0)
  71. // infosCount[ai->playerID][hid]--;
  72. }
  73. bool HeroPtr::operator<(const HeroPtr & rhs) const
  74. {
  75. return hid < rhs.hid;
  76. }
  77. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull) const
  78. {
  79. //TODO? check if these all assertions every time we get info about hero affect efficiency
  80. //
  81. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  82. assert(doWeExpectNull || h);
  83. if(h)
  84. {
  85. auto obj = cb->getObj(hid);
  86. const bool owned = obj && obj->tempOwner == ai->playerID;
  87. if(doWeExpectNull && !owned)
  88. {
  89. return nullptr;
  90. }
  91. else
  92. {
  93. assert(obj);
  94. assert(owned);
  95. }
  96. }
  97. return h;
  98. }
  99. const CGHeroInstance * HeroPtr::operator->() const
  100. {
  101. return get();
  102. }
  103. bool HeroPtr::validAndSet() const
  104. {
  105. return get(true);
  106. }
  107. const CGHeroInstance * HeroPtr::operator*() const
  108. {
  109. return get();
  110. }
  111. bool HeroPtr::operator==(const HeroPtr & rhs) const
  112. {
  113. return h == rhs.get(true);
  114. }
  115. void foreach_tile_pos(std::function<void(const int3 & pos)> foo)
  116. {
  117. // some micro-optimizations since this function gets called a LOT
  118. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  119. int3 mapSize = cb->getMapSize();
  120. for(int i = 0; i < mapSize.x; i++)
  121. {
  122. for(int j = 0; j < mapSize.y; j++)
  123. {
  124. for(int k = 0; k < mapSize.z; k++)
  125. foo(int3(i, j, k));
  126. }
  127. }
  128. }
  129. void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3 & pos)> foo)
  130. {
  131. int3 mapSize = cbp->getMapSize();
  132. for(int i = 0; i < mapSize.x; i++)
  133. {
  134. for(int j = 0; j < mapSize.y; j++)
  135. {
  136. for(int k = 0; k < mapSize.z; k++)
  137. foo(cbp, int3(i, j, k));
  138. }
  139. }
  140. }
  141. void foreach_neighbour(const int3 & pos, std::function<void(const int3 & pos)> foo)
  142. {
  143. CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer
  144. for(const int3 & dir : int3::getDirs())
  145. {
  146. const int3 n = pos + dir;
  147. if(cbp->isInTheMap(n))
  148. foo(pos + dir);
  149. }
  150. }
  151. void foreach_neighbour(CCallback * cbp, const int3 & pos, std::function<void(CCallback * cbp, const int3 & pos)> foo)
  152. {
  153. for(const int3 & dir : int3::getDirs())
  154. {
  155. const int3 n = pos + dir;
  156. if(cbp->isInTheMap(n))
  157. foo(cbp, pos + dir);
  158. }
  159. }
  160. bool CDistanceSorter::operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs) const
  161. {
  162. const CGPathNode * ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos());
  163. const CGPathNode * rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
  164. return ln->cost < rn->cost;
  165. }
  166. bool compareDanger(const CGObjectInstance * lhs, const CGObjectInstance * rhs)
  167. {
  168. return fh->evaluateDanger(lhs) < fh->evaluateDanger(rhs);
  169. }
  170. bool isSafeToVisit(HeroPtr h, crint3 tile)
  171. {
  172. return isSafeToVisit(h, fh->evaluateDanger(tile, h.get()));
  173. }
  174. bool isSafeToVisit(HeroPtr h, uint64_t dangerStrength)
  175. {
  176. const ui64 heroStrength = h->getTotalStrength();
  177. if(dangerStrength)
  178. {
  179. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  180. {
  181. return true;
  182. }
  183. else
  184. {
  185. return false;
  186. }
  187. }
  188. return true; //there's no danger
  189. }
  190. bool isObjectRemovable(const CGObjectInstance * obj)
  191. {
  192. //FIXME: move logic to object property!
  193. switch (obj->ID)
  194. {
  195. case Obj::MONSTER:
  196. case Obj::RESOURCE:
  197. case Obj::CAMPFIRE:
  198. case Obj::TREASURE_CHEST:
  199. case Obj::ARTIFACT:
  200. case Obj::BORDERGUARD:
  201. case Obj::FLOTSAM:
  202. case Obj::PANDORAS_BOX:
  203. case Obj::OCEAN_BOTTLE:
  204. case Obj::SEA_CHEST:
  205. case Obj::SHIPWRECK_SURVIVOR:
  206. case Obj::SPELL_SCROLL:
  207. return true;
  208. break;
  209. default:
  210. return false;
  211. break;
  212. }
  213. }
  214. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  215. {
  216. // TODO: Such information should be provided by pathfinder
  217. // Tile must be free or with unoccupied boat
  218. if(!t->blocked)
  219. {
  220. return true;
  221. }
  222. else if(!fromWater) // do not try to board when in water sector
  223. {
  224. if(t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  225. return true;
  226. }
  227. return false;
  228. }
  229. bool isBlockedBorderGate(int3 tileToHit) //TODO: is that function needed? should be handled by pathfinder
  230. {
  231. if(cb->getTile(tileToHit)->topVisitableId() != Obj::BORDER_GATE)
  232. return false;
  233. auto gate = dynamic_cast<const CGKeys *>(cb->getTile(tileToHit)->topVisitableObj());
  234. return !gate->passableFor(ai->playerID);
  235. }
  236. bool isBlockVisitObj(const int3 & pos)
  237. {
  238. if(auto obj = cb->getTopObj(pos))
  239. {
  240. if(obj->blockVisit) //we can't stand on that object
  241. return true;
  242. }
  243. return false;
  244. }
  245. creInfo infoFromDC(const dwellingContent & dc)
  246. {
  247. creInfo ci;
  248. ci.count = dc.first;
  249. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  250. if (ci.creID != -1)
  251. {
  252. ci.cre = VLC->creh->creatures[ci.creID];
  253. ci.level = ci.cre->level; //this is cretaure tier, while tryRealize expects dwelling level. Ignore.
  254. }
  255. else
  256. {
  257. ci.cre = nullptr;
  258. ci.level = 0;
  259. }
  260. return ci;
  261. }
  262. ui64 howManyReinforcementsCanBuy(const CArmedInstance * h, const CGDwelling * t)
  263. {
  264. ui64 aivalue = 0;
  265. TResources availableRes = cb->getResourceAmount();
  266. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  267. for(auto const dc : t->creatures)
  268. {
  269. creInfo ci = infoFromDC(dc);
  270. if(!ci.count || ci.creID == -1)
  271. continue;
  272. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  273. if(ci.count && ci.creID != -1) //valid creature at this level
  274. {
  275. //can be merged with another stack?
  276. SlotID dst = h->getSlotFor(ci.creID);
  277. if(!h->hasStackAtSlot(dst)) //need another new slot for this stack
  278. {
  279. if(!freeHeroSlots) //no more place for stacks
  280. continue;
  281. else
  282. freeHeroSlots--; //new slot will be occupied
  283. }
  284. //we found matching occupied or free slot
  285. aivalue += ci.count * ci.cre->AIValue;
  286. availableRes -= ci.cre->cost * ci.count;
  287. }
  288. }
  289. return aivalue;
  290. }
  291. ui64 howManyReinforcementsCanGet(const CArmedInstance * h, const CGTownInstance * t)
  292. {
  293. ui64 ret = 0;
  294. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  295. std::vector<const CStackInstance *> toMove;
  296. for(auto const slot : t->Slots())
  297. {
  298. //can be merged woth another stack?
  299. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  300. if(h->hasStackAtSlot(dst))
  301. ret += t->getPower(slot.first);
  302. else
  303. toMove.push_back(slot.second);
  304. }
  305. boost::sort(toMove, [](const CStackInstance * lhs, const CStackInstance * rhs)
  306. {
  307. return lhs->getPower() < rhs->getPower();
  308. });
  309. for(auto & stack : boost::adaptors::reverse(toMove))
  310. {
  311. if(freeHeroSlots)
  312. {
  313. ret += stack->getPower();
  314. freeHeroSlots--;
  315. }
  316. else
  317. break;
  318. }
  319. return ret;
  320. }
  321. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  322. {
  323. return h1->getTotalStrength() < h2->getTotalStrength();
  324. }
  325. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  326. {
  327. return a1->getArmyStrength() < a2->getArmyStrength();
  328. }
  329. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2)
  330. {
  331. auto art1 = a1->artType;
  332. auto art2 = a2->artType;
  333. if(art1->price == art2->price)
  334. return art1->valOfBonuses(Bonus::PRIMARY_SKILL) > art2->valOfBonuses(Bonus::PRIMARY_SKILL);
  335. else if(art1->price > art2->price)
  336. return true;
  337. else
  338. return false;
  339. }