Explore.cpp 9.9 KB

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