AIUtility.cpp 13 KB

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