AIUtility.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #include "StdInc.h"
  2. #include "AIUtility.h"
  3. #include "VCAI.h"
  4. #include "../../lib/UnlockGuard.h"
  5. #include "../../lib/CObjectHandler.h"
  6. #include "../../lib/CConfigHandler.h"
  7. #include "../../lib/CHeroHandler.h"
  8. /*
  9. * AIUtility.cpp, part of VCMI engine
  10. *
  11. * Authors: listed in file AUTHORS in main folder
  12. *
  13. * License: GNU General Public License v2.0 or later
  14. * Full text of license available in license.txt file, in main folder
  15. *
  16. */
  17. extern boost::thread_specific_ptr<CCallback> cb;
  18. extern boost::thread_specific_ptr<VCAI> ai;
  19. extern FuzzyHelper *fh;
  20. //extern static const int3 dirs[8];
  21. void foreach_tile_pos(std::function<void(const int3& pos)> foo)
  22. {
  23. for(int i = 0; i < cb->getMapSize().x; i++)
  24. for(int j = 0; j < cb->getMapSize().y; j++)
  25. for(int k = 0; k < cb->getMapSize().z; k++)
  26. foo(int3(i,j,k));
  27. }
  28. void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
  29. {
  30. for(const int3 &dir : dirs)
  31. {
  32. const int3 n = pos + dir;
  33. if(cb->isInTheMap(n))
  34. foo(pos+dir);
  35. }
  36. }
  37. std::string strFromInt3(int3 pos)
  38. {
  39. std::ostringstream oss;
  40. oss << pos;
  41. return oss.str();
  42. }
  43. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  44. {
  45. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  46. if(ln->turns != rn->turns)
  47. return ln->turns < rn->turns;
  48. return (ln->moveRemains > rn->moveRemains);
  49. }
  50. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  51. {
  52. return lhs->movement > rhs->movement;
  53. }
  54. ui64 evaluateDanger(crint3 tile)
  55. {
  56. const TerrainTile *t = cb->getTile(tile, false);
  57. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  58. return 190000000; //MUCH
  59. ui64 objectDanger = 0, guardDanger = 0;
  60. auto visObjs = cb->getVisitableObjs(tile);
  61. if(visObjs.size())
  62. objectDanger = evaluateDanger(visObjs.back());
  63. int3 guardPos = cb->guardingCreaturePosition(tile);
  64. if(guardPos.x >= 0 && guardPos != tile)
  65. guardDanger = evaluateDanger(guardPos);
  66. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  67. return std::max(objectDanger, guardDanger);
  68. }
  69. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  70. {
  71. const TerrainTile *t = cb->getTile(tile, false);
  72. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  73. return 190000000; //MUCH
  74. ui64 objectDanger = 0, guardDanger = 0;
  75. auto visitableObjects = cb->getVisitableObjs(tile);
  76. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  77. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  78. vstd::erase_if(visitableObjects, [](const CGObjectInstance * obj)
  79. {
  80. return !objWithID<Obj::HERO>(obj);
  81. });
  82. if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
  83. {
  84. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  85. if (objectDanger)
  86. {
  87. //TODO: don't downcast objects AI shouldnt know about!
  88. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  89. if(armedObj)
  90. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  91. }
  92. }
  93. auto guards = cb->getGuardingCreatures(tile);
  94. for (auto cre : guards)
  95. {
  96. vstd::amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  97. }
  98. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  99. return std::max(objectDanger, guardDanger);
  100. }
  101. ui64 evaluateDanger(const CGObjectInstance *obj)
  102. {
  103. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  104. return 0;
  105. switch(obj->ID)
  106. {
  107. case Obj::HERO:
  108. {
  109. InfoAboutHero iah;
  110. cb->getHeroInfo(obj, iah);
  111. return iah.army.getStrength();
  112. }
  113. case Obj::TOWN:
  114. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  115. {
  116. InfoAboutTown iat;
  117. cb->getTownInfo(obj, iat);
  118. return iat.army.getStrength();
  119. }
  120. case Obj::MONSTER:
  121. {
  122. //TODO!!!!!!!!
  123. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  124. return cre->getArmyStrength();
  125. }
  126. case Obj::CREATURE_GENERATOR1:
  127. {
  128. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  129. return d->getArmyStrength();
  130. }
  131. case Obj::MINE:
  132. case Obj::ABANDONED_MINE:
  133. {
  134. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  135. return a->getArmyStrength();
  136. }
  137. case Obj::CRYPT: //crypt
  138. case Obj::CREATURE_BANK: //crebank
  139. case Obj::DRAGON_UTOPIA:
  140. case Obj::SHIPWRECK: //shipwreck
  141. case Obj::DERELICT_SHIP: //derelict ship
  142. // case Obj::PYRAMID:
  143. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  144. case Obj::PYRAMID:
  145. {
  146. if(obj->subID == 0)
  147. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  148. else
  149. return 0;
  150. }
  151. default:
  152. return 0;
  153. }
  154. }
  155. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  156. {
  157. return evaluateDanger(lhs) < evaluateDanger(rhs);
  158. }
  159. bool isSafeToVisit(HeroPtr h, crint3 tile)
  160. {
  161. const ui64 heroStrength = h->getTotalStrength(),
  162. dangerStrength = evaluateDanger(tile, *h);
  163. if(dangerStrength)
  164. {
  165. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  166. {
  167. logAi->traceStream() << boost::format("It's safe for %s to visit tile %s") % h->name % tile;
  168. return true;
  169. }
  170. else
  171. return false;
  172. }
  173. return true; //there's no danger
  174. }
  175. bool isReachable(const CGObjectInstance *obj)
  176. {
  177. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  178. }
  179. bool canBeEmbarkmentPoint(const TerrainTile *t)
  180. {
  181. //tile must be free of with unoccupied boat
  182. return !t->blocked
  183. || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  184. }
  185. int3 whereToExplore(HeroPtr h)
  186. {
  187. TimeCheck tc ("where to explore");
  188. //TODO it's stupid and ineffective, write sth better
  189. cb->setSelection(*h);
  190. int radius = h->getSightRadious();
  191. int3 hpos = h->visitablePos();
  192. //look for nearby objs -> visit them if they're close enouh
  193. const int DIST_LIMIT = 3;
  194. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  195. for (int x = hpos.x - DIST_LIMIT; x <= hpos.y + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
  196. {
  197. for (int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  198. {
  199. for (auto obj : cb->getVisitableObjs (int3(x,y,hpos.z), false))
  200. {
  201. int3 op = obj->visitablePos();
  202. CGPath p;
  203. cb->getPath2(op, p);
  204. if (p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  205. if (ai->isGoodForVisit(obj, h))
  206. nearbyVisitableObjs.push_back(obj);
  207. }
  208. }
  209. }
  210. removeDuplicates (nearbyVisitableObjs); //one object may occupy multiple tiles
  211. boost::sort(nearbyVisitableObjs, isCloser);
  212. if(nearbyVisitableObjs.size())
  213. return nearbyVisitableObjs.back()->visitablePos();
  214. try
  215. {
  216. return ai->explorationBestNeighbour(hpos, radius, h);
  217. }
  218. catch(cannotFulfillGoalException &e)
  219. {
  220. return ai->explorationNewPoint(radius, h);
  221. }
  222. }
  223. bool isBlockedBorderGate(int3 tileToHit)
  224. {
  225. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  226. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  227. }
  228. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  229. { //TODO: do not explore dead-end boundaries
  230. int ret = 0;
  231. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  232. {
  233. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  234. {
  235. int3 npos = int3(x,y,pos.z);
  236. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  237. {
  238. if (!boundaryBetweenTwoPoints (pos, npos))
  239. ret++;
  240. }
  241. }
  242. }
  243. return ret;
  244. }
  245. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2) //determines if two points are separated by known barrier
  246. {
  247. int xMin = std::min (pos1.x, pos2.x);
  248. int xMax = std::max (pos1.x, pos2.x);
  249. int yMin = std::min (pos1.y, pos2.y);
  250. int yMax = std::max (pos1.y, pos2.y);
  251. for (int x = xMin; x <= xMax; ++x)
  252. {
  253. for (int y = yMin; y <= yMax; ++y)
  254. {
  255. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  256. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  257. {
  258. if (!(cb->isVisible(tile) && cb->getTile(tile)->blocked)) //if there's invisible or unblocked tile inbetween, it's good
  259. return false;
  260. }
  261. }
  262. }
  263. return true; //if all are visible and blocked, we're at dead end
  264. }
  265. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  266. {
  267. return howManyTilesWillBeDiscovered(pos + dir, radious);
  268. }
  269. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  270. {
  271. for(const int3 &tile : tiles)
  272. {
  273. foreach_neighbour(tile, [&](int3 neighbour)
  274. {
  275. if(cb->isVisible(neighbour))
  276. out.push_back(neighbour);
  277. });
  278. }
  279. }
  280. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  281. {
  282. ui64 ret = 0;
  283. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  284. std::vector<const CStackInstance *> toMove;
  285. for(auto const slot : t->Slots())
  286. {
  287. //can be merged woth another stack?
  288. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  289. if(h->hasStackAtSlot(dst))
  290. ret += t->getPower(slot.first);
  291. else
  292. toMove.push_back(slot.second);
  293. }
  294. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  295. {
  296. return lhs->getPower() < rhs->getPower();
  297. });
  298. for (auto & stack : boost::adaptors::reverse(toMove))
  299. {
  300. if(freeHeroSlots)
  301. {
  302. ret += stack->getPower();
  303. freeHeroSlots--;
  304. }
  305. else
  306. break;
  307. }
  308. return ret;
  309. }
  310. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  311. {
  312. return h1->getTotalStrength() < h2->getTotalStrength();
  313. }
  314. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  315. {
  316. return a1->getArmyStrength() < a2->getArmyStrength();
  317. }