AIUtility.cpp 13 KB

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