AIUtility.cpp 15 KB

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