AIUtility.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #include "StdInc.h"
  2. #include "AIUtility.h"
  3. #include "VCAI.h"
  4. #include "../../lib/UnlockGuard.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #include "../../lib/CHeroHandler.h"
  7. /*
  8. * AIUtility.cpp, part of VCMI engine
  9. *
  10. * Authors: listed in file AUTHORS in main folder
  11. *
  12. * License: GNU General Public License v2.0 or later
  13. * Full text of license available in license.txt file, in main folder
  14. *
  15. */
  16. extern boost::thread_specific_ptr<CCallback> cb;
  17. extern boost::thread_specific_ptr<VCAI> ai;
  18. extern FuzzyHelper *fh;
  19. //extern static const int3 dirs[8];
  20. const CGObjectInstance * ObjectIdRef::operator->() const
  21. {
  22. return cb->getObj(id, false);
  23. }
  24. ObjectIdRef::operator const CGObjectInstance*() const
  25. {
  26. return cb->getObj(id, false);
  27. }
  28. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
  29. {
  30. }
  31. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  32. {
  33. }
  34. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  35. {
  36. return id < rhs.id;
  37. }
  38. HeroPtr::HeroPtr(const CGHeroInstance *H)
  39. {
  40. if(!H)
  41. {
  42. //init from nullptr should equal to default init
  43. *this = HeroPtr();
  44. return;
  45. }
  46. h = H;
  47. name = h->name;
  48. hid = H->id;
  49. // infosCount[ai->playerID][hid]++;
  50. }
  51. HeroPtr::HeroPtr()
  52. {
  53. h = nullptr;
  54. hid = ObjectInstanceID();
  55. }
  56. HeroPtr::~HeroPtr()
  57. {
  58. // if(hid >= 0)
  59. // infosCount[ai->playerID][hid]--;
  60. }
  61. bool HeroPtr::operator<(const HeroPtr &rhs) const
  62. {
  63. return hid < rhs.hid;
  64. }
  65. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  66. {
  67. //TODO? check if these all assertions every time we get info about hero affect efficiency
  68. //
  69. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  70. assert(doWeExpectNull || h);
  71. if(h)
  72. {
  73. auto obj = cb->getObj(hid);
  74. const bool owned = obj && obj->tempOwner == ai->playerID;
  75. if(doWeExpectNull && !owned)
  76. {
  77. return nullptr;
  78. }
  79. else
  80. {
  81. assert(obj);
  82. assert(owned);
  83. }
  84. }
  85. return h;
  86. }
  87. const CGHeroInstance * HeroPtr::operator->() const
  88. {
  89. return get();
  90. }
  91. bool HeroPtr::validAndSet() const
  92. {
  93. return get(true);
  94. }
  95. const CGHeroInstance * HeroPtr::operator*() const
  96. {
  97. return get();
  98. }
  99. void foreach_tile_pos(std::function<void(const int3& pos)> foo)
  100. {
  101. // some micro-optimizations since this function gets called a LOT
  102. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  103. int3 mapSize = cb->getMapSize();
  104. for(int i = 0; i < mapSize.x; i++)
  105. for(int j = 0; j < mapSize.y; j++)
  106. for(int k = 0; k < mapSize.z; k++)
  107. foo(int3(i,j,k));
  108. }
  109. void foreach_tile_pos(CCallback * cbp, std::function<void(CCallback * cbp, const int3& pos)> foo)
  110. {
  111. int3 mapSize = cbp->getMapSize();
  112. for(int i = 0; i < mapSize.x; i++)
  113. for(int j = 0; j < mapSize.y; j++)
  114. for(int k = 0; k < mapSize.z; k++)
  115. foo(cbp, int3(i,j,k));
  116. }
  117. void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
  118. {
  119. CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer
  120. for(const int3 &dir : dirs)
  121. {
  122. const int3 n = pos + dir;
  123. if(cbp->isInTheMap(n))
  124. foo(pos+dir);
  125. }
  126. }
  127. void foreach_neighbour(CCallback * cbp, const int3 &pos, std::function<void(CCallback * cbp, const int3& pos)> foo)
  128. {
  129. for(const int3 &dir : dirs)
  130. {
  131. const int3 n = pos + dir;
  132. if(cbp->isInTheMap(n))
  133. foo(cbp, pos+dir);
  134. }
  135. }
  136. std::string strFromInt3(int3 pos)
  137. {
  138. std::ostringstream oss;
  139. oss << pos;
  140. return oss.str();
  141. }
  142. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  143. {
  144. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  145. if(ln->turns != rn->turns)
  146. return ln->turns < rn->turns;
  147. return (ln->moveRemains > rn->moveRemains);
  148. }
  149. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  150. {
  151. return lhs->movement > rhs->movement;
  152. }
  153. ui64 evaluateDanger(crint3 tile)
  154. {
  155. const TerrainTile *t = cb->getTile(tile, false);
  156. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  157. return 190000000; //MUCH
  158. ui64 objectDanger = 0, guardDanger = 0;
  159. auto visObjs = cb->getVisitableObjs(tile);
  160. if(visObjs.size())
  161. objectDanger = evaluateDanger(visObjs.back());
  162. int3 guardPos = cb->getGuardingCreaturePosition(tile);
  163. if(guardPos.x >= 0 && guardPos != tile)
  164. guardDanger = evaluateDanger(guardPos);
  165. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  166. return std::max(objectDanger, guardDanger);
  167. }
  168. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  169. {
  170. const TerrainTile *t = cb->getTile(tile, false);
  171. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  172. return 190000000; //MUCH
  173. ui64 objectDanger = 0, guardDanger = 0;
  174. auto visitableObjects = cb->getVisitableObjs(tile);
  175. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  176. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  177. vstd::erase_if(visitableObjects, [](const CGObjectInstance * obj)
  178. {
  179. return !objWithID<Obj::HERO>(obj);
  180. });
  181. if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
  182. {
  183. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  184. if (objectDanger)
  185. {
  186. //TODO: don't downcast objects AI shouldn't know about!
  187. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  188. if(armedObj)
  189. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  190. }
  191. if (dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
  192. { //check guard on the other side of the gate
  193. auto it = ai->knownSubterraneanGates.find(dangerousObject);
  194. if (it != ai->knownSubterraneanGates.end())
  195. {
  196. auto guards = cb->getGuardingCreatures(it->second->visitablePos());
  197. for (auto cre : guards)
  198. {
  199. vstd::amax (guardDanger, evaluateDanger(cre) *
  200. fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre)));
  201. }
  202. }
  203. }
  204. }
  205. auto guards = cb->getGuardingCreatures(tile);
  206. for (auto cre : guards)
  207. {
  208. vstd::amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  209. }
  210. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  211. return std::max(objectDanger, guardDanger);
  212. }
  213. ui64 evaluateDanger(const CGObjectInstance *obj)
  214. {
  215. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  216. return 0;
  217. switch(obj->ID)
  218. {
  219. case Obj::HERO:
  220. {
  221. InfoAboutHero iah;
  222. cb->getHeroInfo(obj, iah);
  223. return iah.army.getStrength();
  224. }
  225. case Obj::TOWN:
  226. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  227. {
  228. InfoAboutTown iat;
  229. cb->getTownInfo(obj, iat);
  230. return iat.army.getStrength();
  231. }
  232. case Obj::MONSTER:
  233. {
  234. //TODO!!!!!!!!
  235. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  236. return cre->getArmyStrength();
  237. }
  238. case Obj::CREATURE_GENERATOR1:
  239. {
  240. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  241. return d->getArmyStrength();
  242. }
  243. case Obj::MINE:
  244. case Obj::ABANDONED_MINE:
  245. {
  246. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  247. return a->getArmyStrength();
  248. }
  249. case Obj::CRYPT: //crypt
  250. case Obj::CREATURE_BANK: //crebank
  251. case Obj::DRAGON_UTOPIA:
  252. case Obj::SHIPWRECK: //shipwreck
  253. case Obj::DERELICT_SHIP: //derelict ship
  254. // case Obj::PYRAMID:
  255. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  256. case Obj::PYRAMID:
  257. {
  258. if(obj->subID == 0)
  259. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  260. else
  261. return 0;
  262. }
  263. default:
  264. return 0;
  265. }
  266. }
  267. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  268. {
  269. return evaluateDanger(lhs) < evaluateDanger(rhs);
  270. }
  271. bool isSafeToVisit(HeroPtr h, crint3 tile)
  272. {
  273. const ui64 heroStrength = h->getTotalStrength(),
  274. dangerStrength = evaluateDanger(tile, *h);
  275. if(dangerStrength)
  276. {
  277. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  278. {
  279. logAi->traceStream() << boost::format("It's safe for %s to visit tile %s") % h->name % tile;
  280. return true;
  281. }
  282. else
  283. return false;
  284. }
  285. return true; //there's no danger
  286. }
  287. bool isReachable(const CGObjectInstance *obj)
  288. {
  289. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  290. }
  291. bool canBeEmbarkmentPoint(const TerrainTile *t, bool fromWater)
  292. {
  293. //tile must be free of with unoccupied boat
  294. return !t->blocked
  295. || (!fromWater && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  296. //do not try to board when in water sector
  297. }
  298. int3 whereToExplore(HeroPtr h)
  299. {
  300. TimeCheck tc ("where to explore");
  301. cb->setSelection(*h);
  302. int radius = h->getSightRadious();
  303. int3 hpos = h->visitablePos();
  304. //look for nearby objs -> visit them if they're close enouh
  305. const int DIST_LIMIT = 3;
  306. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  307. for (int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
  308. {
  309. for (int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  310. {
  311. for (auto obj : cb->getVisitableObjs (int3(x,y,hpos.z), false))
  312. {
  313. int3 op = obj->visitablePos();
  314. CGPath p;
  315. cb->getPath2(op, p);
  316. if (p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  317. if (ai->isGoodForVisit(obj, h))
  318. nearbyVisitableObjs.push_back(obj);
  319. }
  320. }
  321. }
  322. removeDuplicates (nearbyVisitableObjs); //one object may occupy multiple tiles
  323. boost::sort(nearbyVisitableObjs, isCloser);
  324. if(nearbyVisitableObjs.size())
  325. return nearbyVisitableObjs.back()->visitablePos();
  326. try //check if nearby tiles allow us to reveal anything - this is quick
  327. {
  328. return ai->explorationBestNeighbour(hpos, radius, h);
  329. }
  330. catch(cannotFulfillGoalException &e)
  331. {
  332. //perform exhaustive search
  333. return ai->explorationNewPoint(h);
  334. }
  335. }
  336. bool isBlockedBorderGate(int3 tileToHit)
  337. {
  338. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  339. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  340. }
  341. int howManyTilesWillBeDiscovered(const int3 &pos, int radious, CCallback * cbp)
  342. { //TODO: do not explore dead-end boundaries
  343. int ret = 0;
  344. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  345. {
  346. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  347. {
  348. int3 npos = int3(x,y,pos.z);
  349. if(cbp->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cbp->isVisible(npos))
  350. {
  351. if (!boundaryBetweenTwoPoints (pos, npos, cbp))
  352. ret++;
  353. }
  354. }
  355. }
  356. return ret;
  357. }
  358. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2, CCallback * cbp) //determines if two points are separated by known barrier
  359. {
  360. int xMin = std::min (pos1.x, pos2.x);
  361. int xMax = std::max (pos1.x, pos2.x);
  362. int yMin = std::min (pos1.y, pos2.y);
  363. int yMax = std::max (pos1.y, pos2.y);
  364. for (int x = xMin; x <= xMax; ++x)
  365. {
  366. for (int y = yMin; y <= yMax; ++y)
  367. {
  368. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  369. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  370. {
  371. if (!(cbp->isVisible(tile) && cbp->getTile(tile)->blocked)) //if there's invisible or unblocked tile between, it's good
  372. return false;
  373. }
  374. }
  375. }
  376. return true; //if all are visible and blocked, we're at dead end
  377. }
  378. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  379. {
  380. return howManyTilesWillBeDiscovered(pos + dir, radious, cb.get());
  381. }
  382. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  383. {
  384. for(const int3 &tile : tiles)
  385. {
  386. foreach_neighbour(tile, [&](int3 neighbour)
  387. {
  388. if(cb->isVisible(neighbour))
  389. out.push_back(neighbour);
  390. });
  391. }
  392. }
  393. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  394. {
  395. ui64 ret = 0;
  396. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  397. std::vector<const CStackInstance *> toMove;
  398. for(auto const slot : t->Slots())
  399. {
  400. //can be merged woth another stack?
  401. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  402. if(h->hasStackAtSlot(dst))
  403. ret += t->getPower(slot.first);
  404. else
  405. toMove.push_back(slot.second);
  406. }
  407. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  408. {
  409. return lhs->getPower() < rhs->getPower();
  410. });
  411. for (auto & stack : boost::adaptors::reverse(toMove))
  412. {
  413. if(freeHeroSlots)
  414. {
  415. ret += stack->getPower();
  416. freeHeroSlots--;
  417. }
  418. else
  419. break;
  420. }
  421. return ret;
  422. }
  423. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  424. {
  425. return h1->getTotalStrength() < h2->getTotalStrength();
  426. }
  427. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  428. {
  429. return a1->getArmyStrength() < a2->getArmyStrength();
  430. }