Explore.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. #include "../../../lib/CPlayerState.h"
  22. extern boost::thread_specific_ptr<CCallback> cb;
  23. extern boost::thread_specific_ptr<VCAI> ai;
  24. extern FuzzyHelper * fh;
  25. using namespace Goals;
  26. namespace Goals
  27. {
  28. struct ExplorationHelper
  29. {
  30. HeroPtr hero;
  31. int sightRadius;
  32. float bestValue;
  33. TSubgoal bestGoal;
  34. VCAI * aip;
  35. CCallback * cbp;
  36. const TeamState * ts;
  37. int3 ourPos;
  38. bool allowDeadEndCancellation;
  39. bool allowGatherArmy;
  40. ExplorationHelper(HeroPtr h, bool gatherArmy)
  41. {
  42. cbp = cb.get();
  43. aip = ai.get();
  44. hero = h;
  45. ts = cbp->getPlayerTeam(ai->playerID);
  46. sightRadius = hero->getSightRadius();
  47. bestGoal = sptr(Goals::Invalid());
  48. bestValue = 0;
  49. ourPos = h->visitablePos();
  50. allowDeadEndCancellation = true;
  51. allowGatherArmy = gatherArmy;
  52. }
  53. void scanSector(int scanRadius)
  54. {
  55. int3 tile = int3(0, 0, ourPos.z);
  56. const auto & slice = (*(ts->fogOfWarMap))[ourPos.z];
  57. for(tile.x = ourPos.x - scanRadius; tile.x <= ourPos.x + scanRadius; tile.x++)
  58. {
  59. for(tile.y = ourPos.y - scanRadius; tile.y <= ourPos.y + scanRadius; tile.y++)
  60. {
  61. if(cbp->isInTheMap(tile) && slice[tile.x][tile.y])
  62. {
  63. scanTile(tile);
  64. }
  65. }
  66. }
  67. }
  68. void scanMap()
  69. {
  70. int3 mapSize = cbp->getMapSize();
  71. int perimeter = 2 * sightRadius * (mapSize.x + mapSize.y);
  72. std::vector<int3> from;
  73. std::vector<int3> to;
  74. from.reserve(perimeter);
  75. to.reserve(perimeter);
  76. foreach_tile_pos([&](const int3 & pos)
  77. {
  78. if((*(ts->fogOfWarMap))[pos.z][pos.x][pos.y])
  79. {
  80. bool hasInvisibleNeighbor = false;
  81. foreach_neighbour(cbp, pos, [&](CCallback * cbp, int3 neighbour)
  82. {
  83. if(!(*(ts->fogOfWarMap))[neighbour.z][neighbour.x][neighbour.y])
  84. {
  85. hasInvisibleNeighbor = true;
  86. }
  87. });
  88. if(hasInvisibleNeighbor)
  89. from.push_back(pos);
  90. }
  91. });
  92. logAi->debug("Exploration scan visible area perimeter for hero %s", hero.name);
  93. for(const int3 & tile : from)
  94. {
  95. scanTile(tile);
  96. }
  97. if(!bestGoal->invalid())
  98. {
  99. return;
  100. }
  101. allowDeadEndCancellation = false;
  102. for(int i = 0; i < sightRadius; i++)
  103. {
  104. getVisibleNeighbours(from, to);
  105. vstd::concatenate(from, to);
  106. vstd::removeDuplicates(from);
  107. }
  108. logAi->debug("Exploration scan all possible tiles for hero %s", hero.name);
  109. for(const int3 & tile : from)
  110. {
  111. scanTile(tile);
  112. }
  113. }
  114. void scanTile(const int3 & tile)
  115. {
  116. if(tile == ourPos
  117. || !aip->ah->isTileAccessible(hero, tile)) //shouldn't happen, but it does
  118. return;
  119. int tilesDiscovered = howManyTilesWillBeDiscovered(tile);
  120. if(!tilesDiscovered)
  121. return;
  122. auto waysToVisit = aip->ah->howToVisitTile(hero, tile, allowGatherArmy);
  123. for(auto goal : waysToVisit)
  124. {
  125. if(goal->evaluationContext.movementCost <= 0.0) // should not happen
  126. continue;
  127. float ourValue = (float)tilesDiscovered * tilesDiscovered / goal->evaluationContext.movementCost;
  128. if(ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  129. {
  130. auto obj = cb->getTopObj(tile);
  131. // picking up resources does not yield any exploration at all.
  132. // if it blocks the way to some explorable tile AIPathfinder will take care of it
  133. if(obj && obj->blockVisit)
  134. {
  135. continue;
  136. }
  137. if(isSafeToVisit(hero, tile))
  138. {
  139. bestGoal = goal;
  140. bestValue = ourValue;
  141. }
  142. }
  143. }
  144. }
  145. void getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out) const
  146. {
  147. for(const int3 & tile : tiles)
  148. {
  149. foreach_neighbour(cbp, tile, [&](CCallback * cbp, int3 neighbour)
  150. {
  151. if((*(ts->fogOfWarMap))[neighbour.z][neighbour.x][neighbour.y])
  152. {
  153. out.push_back(neighbour);
  154. }
  155. });
  156. }
  157. }
  158. int howManyTilesWillBeDiscovered(const int3 & pos) const
  159. {
  160. int ret = 0;
  161. int3 npos = int3(0, 0, pos.z);
  162. const auto & slice = (*(ts->fogOfWarMap))[pos.z];
  163. for(npos.x = pos.x - sightRadius; npos.x <= pos.x + sightRadius; npos.x++)
  164. {
  165. for(npos.y = pos.y - sightRadius; npos.y <= pos.y + sightRadius; npos.y++)
  166. {
  167. if(cbp->isInTheMap(npos)
  168. && pos.dist2d(npos) - 0.5 < sightRadius
  169. && !slice[npos.x][npos.y])
  170. {
  171. if(allowDeadEndCancellation
  172. && !hasReachableNeighbor(npos))
  173. {
  174. continue;
  175. }
  176. ret++;
  177. }
  178. }
  179. }
  180. return ret;
  181. }
  182. bool hasReachableNeighbor(const int3 &pos) const
  183. {
  184. for(crint3 dir : int3::getDirs())
  185. {
  186. int3 tile = pos + dir;
  187. if(cbp->isInTheMap(tile))
  188. {
  189. auto isAccessible = aip->ah->isTileAccessible(hero, tile);
  190. if(isAccessible)
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. };
  197. }
  198. bool Explore::operator==(const Explore & other) const
  199. {
  200. return other.hero.h == hero.h && other.allowGatherArmy == allowGatherArmy;
  201. }
  202. std::string Explore::completeMessage() const
  203. {
  204. return "Hero " + hero.get()->getNameTranslated() + " completed exploration";
  205. }
  206. TSubgoal Explore::whatToDoToAchieve()
  207. {
  208. return fh->chooseSolution(getAllPossibleSubgoals());
  209. }
  210. TGoalVec Explore::getAllPossibleSubgoals()
  211. {
  212. TGoalVec ret;
  213. std::vector<const CGHeroInstance *> heroes;
  214. if(hero)
  215. {
  216. heroes.push_back(hero.h);
  217. }
  218. else
  219. {
  220. //heroes = ai->getUnblockedHeroes();
  221. heroes = cb->getHeroesInfo();
  222. vstd::erase_if(heroes, [](const HeroPtr h)
  223. {
  224. if(ai->getGoal(h)->goalType == EXPLORE) //do not reassign hero who is already explorer
  225. return true;
  226. if(!ai->isAbleToExplore(h))
  227. return true;
  228. return !h->movement; //saves time, immobile heroes are useless anyway
  229. });
  230. }
  231. //try to use buildings that uncover map
  232. std::vector<const CGObjectInstance *> objs;
  233. for(auto obj : ai->visitableObjs)
  234. {
  235. if(!vstd::contains(ai->alreadyVisited, obj))
  236. {
  237. switch(obj->ID.num)
  238. {
  239. case Obj::REDWOOD_OBSERVATORY:
  240. case Obj::PILLAR_OF_FIRE:
  241. case Obj::CARTOGRAPHER:
  242. objs.push_back(obj);
  243. break;
  244. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  245. case Obj::MONOLITH_TWO_WAY:
  246. case Obj::SUBTERRANEAN_GATE:
  247. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  248. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  249. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  250. objs.push_back(obj);
  251. break;
  252. }
  253. }
  254. else
  255. {
  256. switch(obj->ID.num)
  257. {
  258. case Obj::MONOLITH_TWO_WAY:
  259. case Obj::SUBTERRANEAN_GATE:
  260. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  261. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  262. break;
  263. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  264. {
  265. if(!cb->getObj(exit))
  266. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  267. objs.push_back(obj);
  268. break;
  269. }
  270. }
  271. break;
  272. }
  273. }
  274. }
  275. for(auto h : heroes)
  276. {
  277. for(auto obj : objs) //double loop, performance risk?
  278. {
  279. auto waysToVisitObj = ai->ah->howToVisitObj(h, obj, allowGatherArmy);
  280. vstd::concatenate(ret, waysToVisitObj);
  281. }
  282. TSubgoal goal = exploreNearestNeighbour(h);
  283. if(!goal->invalid())
  284. {
  285. ret.push_back(goal);
  286. }
  287. }
  288. if(ret.empty())
  289. {
  290. for(auto h : heroes)
  291. {
  292. logAi->trace("Exploration searching for a new point for hero %s", h->getNameTranslated());
  293. TSubgoal goal = explorationNewPoint(h);
  294. if(goal->invalid())
  295. {
  296. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  297. }
  298. else
  299. {
  300. ret.push_back(goal);
  301. }
  302. }
  303. }
  304. //we either don't have hero yet or none of heroes can explore
  305. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  306. ret.push_back(sptr(RecruitHero()));
  307. if(ret.empty())
  308. {
  309. throw goalFulfilledException(sptr(Explore().sethero(hero)));
  310. }
  311. return ret;
  312. }
  313. bool Explore::fulfillsMe(TSubgoal goal)
  314. {
  315. if(goal->goalType == EXPLORE)
  316. {
  317. if(goal->hero)
  318. return hero == goal->hero;
  319. else
  320. return true; //cancel ALL exploration
  321. }
  322. return false;
  323. }
  324. TSubgoal Explore::explorationBestNeighbour(int3 hpos, HeroPtr h) const
  325. {
  326. ExplorationHelper scanResult(h, allowGatherArmy);
  327. for(crint3 dir : int3::getDirs())
  328. {
  329. int3 tile = hpos + dir;
  330. if(cb->isInTheMap(tile))
  331. {
  332. scanResult.scanTile(tile);
  333. }
  334. }
  335. return scanResult.bestGoal;
  336. }
  337. TSubgoal Explore::explorationNewPoint(HeroPtr h) const
  338. {
  339. ExplorationHelper scanResult(h, allowGatherArmy);
  340. scanResult.scanSector(10);
  341. if(!scanResult.bestGoal->invalid())
  342. {
  343. return scanResult.bestGoal;
  344. }
  345. scanResult.scanMap();
  346. return scanResult.bestGoal;
  347. }
  348. TSubgoal Explore::exploreNearestNeighbour(HeroPtr h) const
  349. {
  350. TimeCheck tc("where to explore");
  351. int3 hpos = h->visitablePos();
  352. //look for nearby objs -> visit them if they're close enough
  353. const int DIST_LIMIT = 3;
  354. const float COST_LIMIT = .2f; //todo: fine tune
  355. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  356. 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
  357. {
  358. for(int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  359. {
  360. for(auto obj : cb->getVisitableObjs(int3(x, y, hpos.z), false))
  361. {
  362. if(ai->isGoodForVisit(obj, h, COST_LIMIT))
  363. {
  364. nearbyVisitableObjs.push_back(obj);
  365. }
  366. }
  367. }
  368. }
  369. if(nearbyVisitableObjs.size())
  370. {
  371. vstd::removeDuplicates(nearbyVisitableObjs); //one object may occupy multiple tiles
  372. boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
  373. TSubgoal pickupNearestObj = fh->chooseSolution(ai->ah->howToVisitObj(h, nearbyVisitableObjs.back(), false));
  374. if(!pickupNearestObj->invalid())
  375. {
  376. return pickupNearestObj;
  377. }
  378. }
  379. //check if nearby tiles allow us to reveal anything - this is quick
  380. return explorationBestNeighbour(hpos, h);
  381. }