AIUtility.cpp 13 KB

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