Explore.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * Explore.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 "Goals.h"
  12. #include "../VCAI.h"
  13. #include "../AIUtility.h"
  14. #include "../AIhelper.h"
  15. #include "../FuzzyHelper.h"
  16. #include "../ResourceManager.h"
  17. #include "../BuildingManager.h"
  18. #include "../../../lib/mapping/CMap.h" //for victory conditions
  19. #include "../../../lib/CPathfinder.h"
  20. #include "../../../lib/StringConstants.h"
  21. extern boost::thread_specific_ptr<CCallback> cb;
  22. extern boost::thread_specific_ptr<VCAI> ai;
  23. extern FuzzyHelper * fh;
  24. using namespace Goals;
  25. bool Explore::operator==(const Explore & other) const
  26. {
  27. return other.hero.h == hero.h;
  28. }
  29. std::string Explore::completeMessage() const
  30. {
  31. return "Hero " + hero.get()->name + " completed exploration";
  32. }
  33. TSubgoal Explore::whatToDoToAchieve()
  34. {
  35. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  36. if(hero) //use best step for this hero
  37. {
  38. return ret;
  39. }
  40. else
  41. {
  42. if(ret->hero.get(true))
  43. return sptr(Explore().sethero(ret->hero.h)); //choose this hero and then continue with him
  44. else
  45. return ret; //other solutions, like buying hero from tavern
  46. }
  47. }
  48. TGoalVec Explore::getAllPossibleSubgoals()
  49. {
  50. TGoalVec ret;
  51. std::vector<const CGHeroInstance *> heroes;
  52. if(hero)
  53. {
  54. heroes.push_back(hero.h);
  55. }
  56. else
  57. {
  58. //heroes = ai->getUnblockedHeroes();
  59. heroes = cb->getHeroesInfo();
  60. vstd::erase_if(heroes, [](const HeroPtr h)
  61. {
  62. if(ai->getGoal(h)->goalType == EXPLORE) //do not reassign hero who is already explorer
  63. return true;
  64. if(!ai->isAbleToExplore(h))
  65. return true;
  66. return !h->movement; //saves time, immobile heroes are useless anyway
  67. });
  68. }
  69. //try to use buildings that uncover map
  70. std::vector<const CGObjectInstance *> objs;
  71. for(auto obj : ai->visitableObjs)
  72. {
  73. if(!vstd::contains(ai->alreadyVisited, obj))
  74. {
  75. switch(obj->ID.num)
  76. {
  77. case Obj::REDWOOD_OBSERVATORY:
  78. case Obj::PILLAR_OF_FIRE:
  79. case Obj::CARTOGRAPHER:
  80. objs.push_back(obj);
  81. break;
  82. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  83. case Obj::MONOLITH_TWO_WAY:
  84. case Obj::SUBTERRANEAN_GATE:
  85. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  86. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  87. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  88. objs.push_back(obj);
  89. break;
  90. }
  91. }
  92. else
  93. {
  94. switch(obj->ID.num)
  95. {
  96. case Obj::MONOLITH_TWO_WAY:
  97. case Obj::SUBTERRANEAN_GATE:
  98. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  99. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  100. break;
  101. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  102. {
  103. if(!cb->getObj(exit))
  104. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  105. objs.push_back(obj);
  106. break;
  107. }
  108. }
  109. break;
  110. }
  111. }
  112. }
  113. auto primaryHero = ai->primaryHero().h;
  114. for(auto h : heroes)
  115. {
  116. for(auto obj : objs) //double loop, performance risk?
  117. {
  118. auto waysToVisitObj = ai->ah->howToVisitObj(h, obj);
  119. vstd::concatenate(ret, waysToVisitObj);
  120. }
  121. TSubgoal goal = howToExplore(h);
  122. if(goal->invalid())
  123. {
  124. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  125. }
  126. else
  127. {
  128. ret.push_back(goal);
  129. }
  130. }
  131. //we either don't have hero yet or none of heroes can explore
  132. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  133. ret.push_back(sptr(RecruitHero()));
  134. if(ret.empty())
  135. {
  136. throw goalFulfilledException(sptr(Explore().sethero(hero)));
  137. }
  138. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  139. return ret;
  140. }
  141. bool Explore::fulfillsMe(TSubgoal goal)
  142. {
  143. if(goal->goalType == EXPLORE)
  144. {
  145. if(goal->hero)
  146. return hero == goal->hero;
  147. else
  148. return true; //cancel ALL exploration
  149. }
  150. return false;
  151. }
  152. bool Explore::hasReachableNeighbor(const int3 &pos, HeroPtr hero, CCallback * cbp, VCAI * vcai) const
  153. {
  154. for(crint3 dir : int3::getDirs())
  155. {
  156. int3 tile = pos + dir;
  157. if(cbp->isInTheMap(tile))
  158. {
  159. auto paths = vcai->ah->getPathsToTile(hero, tile);
  160. return paths.size();
  161. }
  162. }
  163. return false;
  164. }
  165. int Explore::howManyTilesWillBeDiscovered(
  166. const int3 & pos,
  167. int radious,
  168. CCallback * cbp,
  169. HeroPtr hero,
  170. std::function<bool (const int3 &)> filter) const
  171. {
  172. int ret = 0;
  173. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  174. {
  175. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  176. {
  177. int3 npos = int3(x, y, pos.z);
  178. if(cbp->isInTheMap(npos)
  179. && pos.dist2d(npos) - 0.5 < radious
  180. && !cbp->isVisible(npos)
  181. && filter(npos))
  182. {
  183. ret++;
  184. }
  185. }
  186. }
  187. return ret;
  188. }
  189. TSubgoal Explore::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h) const
  190. {
  191. std::map<int3, int> dstToRevealedTiles;
  192. VCAI * aip = ai.get();
  193. CCallback * cbp = cb.get();
  194. for(crint3 dir : int3::getDirs())
  195. {
  196. int3 tile = hpos + dir;
  197. if(cb->isInTheMap(tile))
  198. {
  199. if(isBlockVisitObj(tile))
  200. continue;
  201. if(isSafeToVisit(h, tile) && ai->isAccessibleForHero(tile, h))
  202. {
  203. auto distance = hpos.dist2d(tile); // diagonal movement opens more tiles but spends more mp
  204. int tilesDiscovered = howManyTilesWillBeDiscovered(tile, radius, cbp, h, [&](int3 neighbor) -> bool {
  205. return hasReachableNeighbor(neighbor, h, cbp, aip);
  206. });
  207. dstToRevealedTiles[tile] = tilesDiscovered / distance;
  208. }
  209. }
  210. }
  211. if(dstToRevealedTiles.empty()) //yes, it DID happen!
  212. return sptr(Invalid());
  213. auto best = dstToRevealedTiles.begin();
  214. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  215. {
  216. const CGPathNode * pn = cb->getPathsInfo(h.get())->getPathInfo(i->first);
  217. //const TerrainTile *t = cb->getTile(i->first);
  218. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  219. best = i;
  220. }
  221. if(best->second)
  222. return sptr(VisitTile(best->first).sethero(h));
  223. return sptr(Invalid());
  224. }
  225. TSubgoal Explore::explorationNewPoint(HeroPtr h) const
  226. {
  227. int radius = h->getSightRadius();
  228. CCallback * cbp = cb.get();
  229. VCAI *aip = ai.get();
  230. std::vector<std::vector<int3>> tiles; //tiles[distance_to_fow]
  231. tiles.resize(radius);
  232. foreach_tile_pos([&](const int3 & pos)
  233. {
  234. if(!cbp->isVisible(pos))
  235. tiles[0].push_back(pos);
  236. });
  237. float bestValue = 0; //discovered tile to node distance ratio
  238. TSubgoal bestWay = sptr(Invalid());
  239. int3 ourPos = h->convertPosition(h->pos, false);
  240. for(int i = 1; i < radius; i++)
  241. {
  242. getVisibleNeighbours(tiles[i - 1], tiles[i], cbp);
  243. vstd::removeDuplicates(tiles[i]);
  244. for(const int3 & tile : tiles[i])
  245. {
  246. if(tile == ourPos) //shouldn't happen, but it does
  247. continue;
  248. auto waysToVisit = aip->ah->howToVisitTile(h, tile);
  249. for(auto goal : waysToVisit)
  250. {
  251. if(goal->evaluationContext.movementCost == 0) // should not happen
  252. continue;
  253. int tilesDiscovered = howManyTilesWillBeDiscovered(tile, radius, cbp, h, [](int3 neighbor) -> bool { return true; });
  254. float ourValue = (float) tilesDiscovered / goal->evaluationContext.movementCost; //+1 prevents erratic jumps
  255. if(ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  256. {
  257. auto obj = cb->getTopObj(tile);
  258. if(obj && obj->blockVisit && !isObjectRemovable(obj)) //we can't stand on that object
  259. {
  260. continue;
  261. }
  262. if(isSafeToVisit(h, tile))
  263. {
  264. bestWay = goal;
  265. bestValue = ourValue;
  266. }
  267. }
  268. }
  269. }
  270. if(!bestWay->invalid())
  271. {
  272. return bestWay;
  273. }
  274. }
  275. return bestWay;
  276. }
  277. TSubgoal Explore::howToExplore(HeroPtr h) const
  278. {
  279. TimeCheck tc("where to explore");
  280. int radius = h->getSightRadius();
  281. int3 hpos = h->visitablePos();
  282. //look for nearby objs -> visit them if they're close enouh
  283. const int DIST_LIMIT = 3;
  284. const int MP_LIMIT = DIST_LIMIT * 150; // aproximate cost of diagonal movement
  285. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  286. 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
  287. {
  288. for(int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  289. {
  290. for(auto obj : cb->getVisitableObjs(int3(x, y, hpos.z), false))
  291. {
  292. if(ai->isGoodForVisit(obj, h, MP_LIMIT))
  293. {
  294. nearbyVisitableObjs.push_back(obj);
  295. }
  296. }
  297. }
  298. }
  299. vstd::removeDuplicates(nearbyVisitableObjs); //one object may occupy multiple tiles
  300. boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
  301. if(nearbyVisitableObjs.size())
  302. {
  303. TSubgoal pickupNearestObj = fh->chooseSolution(ai->ah->howToVisitObj(h, nearbyVisitableObjs.back(), false));
  304. if(!pickupNearestObj->invalid())
  305. {
  306. return pickupNearestObj;
  307. }
  308. }
  309. //check if nearby tiles allow us to reveal anything - this is quick
  310. TSubgoal result = explorationBestNeighbour(hpos, radius, h);
  311. if(result->invalid())
  312. {
  313. //perform exhaustive search
  314. result = explorationNewPoint(h);
  315. }
  316. return result;
  317. }
  318. void Explore::getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out, CCallback * cbp) const
  319. {
  320. for(const int3 & tile : tiles)
  321. {
  322. foreach_neighbour(tile, [&](int3 neighbour)
  323. {
  324. if(cbp->isVisible(neighbour))
  325. {
  326. auto tile = cbp->getTile(neighbour);
  327. if(tile && !tile->blocked)
  328. out.push_back(neighbour);
  329. }
  330. });
  331. }
  332. }