DangerHitMapAnalyzer.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. * DangerHitMapAnalyzer.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 "DangerHitMapAnalyzer.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../pforeach.h"
  14. #include "../../../lib/CRandomGenerator.h"
  15. #include "../../../lib/logging/VisualLogger.h"
  16. namespace NKAI
  17. {
  18. const HitMapInfo HitMapInfo::NoThreat;
  19. double HitMapInfo::value() const
  20. {
  21. return danger / std::sqrt(turn / 3.0f + 1);
  22. }
  23. void logHitmap(PlayerColor playerID, DangerHitMapAnalyzer & data)
  24. {
  25. #if NKAI_TRACE_LEVEL >= 1
  26. logVisual->updateWithLock(playerID.toString() + ".danger.max", [&data](IVisualLogBuilder & b)
  27. {
  28. foreach_tile_pos([&b, &data](const int3 & pos)
  29. {
  30. auto & treat = data.getTileThreat(pos).maximumDanger;
  31. b.addText(pos, std::to_string(treat.danger));
  32. if(treat.hero.validAndSet())
  33. {
  34. b.addText(pos, std::to_string(treat.turn));
  35. b.addText(pos, treat.hero->getNameTranslated());
  36. }
  37. });
  38. });
  39. logVisual->updateWithLock(playerID.toString() + ".danger.fast", [&data](IVisualLogBuilder & b)
  40. {
  41. foreach_tile_pos([&b, &data](const int3 & pos)
  42. {
  43. auto & treat = data.getTileThreat(pos).fastestDanger;
  44. b.addText(pos, std::to_string(treat.danger));
  45. if(treat.hero.validAndSet())
  46. {
  47. b.addText(pos, std::to_string(treat.turn));
  48. b.addText(pos, treat.hero->getNameTranslated());
  49. }
  50. });
  51. });
  52. #endif
  53. }
  54. void DangerHitMapAnalyzer::updateHitMap()
  55. {
  56. if(hitMapUpToDate)
  57. return;
  58. logAi->trace("Update danger hitmap");
  59. hitMapUpToDate = true;
  60. auto start = std::chrono::high_resolution_clock::now();
  61. auto cb = ai->cb.get();
  62. auto mapSize = ai->cb->getMapSize();
  63. if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
  64. hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
  65. enemyHeroAccessibleObjects.clear();
  66. townThreats.clear();
  67. std::map<PlayerColor, std::map<const CGHeroInstance *, HeroRole>> heroes;
  68. for(const CGObjectInstance * obj : ai->memory->visitableObjs)
  69. {
  70. if(obj->ID == Obj::HERO)
  71. {
  72. auto hero = dynamic_cast<const CGHeroInstance *>(obj);
  73. heroes[hero->tempOwner][hero] = HeroRole::MAIN;
  74. }
  75. }
  76. auto ourTowns = cb->getTownsInfo();
  77. for(auto town : ourTowns)
  78. {
  79. townThreats[town->id]; // insert empty list
  80. }
  81. foreach_tile_pos([&](const int3 & pos){
  82. hitMap[pos.x][pos.y][pos.z].reset();
  83. });
  84. for(auto pair : heroes)
  85. {
  86. if(!pair.first.isValidPlayer())
  87. continue;
  88. if(ai->cb->getPlayerRelations(ai->playerID, pair.first) != PlayerRelations::ENEMIES)
  89. continue;
  90. PathfinderSettings ps;
  91. ps.scoutTurnDistanceLimit = ps.mainTurnDistanceLimit = ai->settings->getMainHeroTurnDistanceLimit();
  92. ps.useHeroChain = false;
  93. ai->pathfinder->updatePaths(pair.second, ps);
  94. boost::this_thread::interruption_point();
  95. pforeachTilePaths(mapSize, ai, [&](const int3 & pos, const std::vector<AIPath> & paths)
  96. {
  97. for(const AIPath & path : paths)
  98. {
  99. if(path.getFirstBlockedAction())
  100. continue;
  101. auto & node = hitMap[pos.x][pos.y][pos.z];
  102. HitMapInfo newThreat;
  103. newThreat.hero = path.targetHero;
  104. newThreat.turn = path.turn();
  105. newThreat.danger = path.getHeroStrength();
  106. if(newThreat.value() > node.maximumDanger.value())
  107. {
  108. node.maximumDanger = newThreat;
  109. }
  110. if(newThreat.turn < node.fastestDanger.turn
  111. || (newThreat.turn == node.fastestDanger.turn && node.fastestDanger.danger < newThreat.danger))
  112. {
  113. node.fastestDanger = newThreat;
  114. }
  115. auto objects = cb->getVisitableObjs(pos, false);
  116. for(auto obj : objects)
  117. {
  118. if(obj->ID == Obj::TOWN && obj->getOwner() == ai->playerID)
  119. {
  120. auto & threats = townThreats[obj->id];
  121. auto threat = std::find_if(threats.begin(), threats.end(), [&](const HitMapInfo & i) -> bool
  122. {
  123. return i.hero.hid == path.targetHero->id;
  124. });
  125. if(threat == threats.end())
  126. {
  127. threats.emplace_back();
  128. threat = std::prev(threats.end(), 1);
  129. }
  130. if(newThreat.value() > threat->value())
  131. {
  132. *threat = newThreat;
  133. }
  134. if(newThreat.turn == 0)
  135. {
  136. if(cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES)
  137. enemyHeroAccessibleObjects.emplace_back(path.targetHero, obj);
  138. }
  139. }
  140. }
  141. }
  142. });
  143. }
  144. logAi->trace("Danger hit map updated in %ld", timeElapsed(start));
  145. logHitmap(ai->playerID, *this);
  146. }
  147. void DangerHitMapAnalyzer::calculateTileOwners()
  148. {
  149. if(tileOwnersUpToDate) return;
  150. tileOwnersUpToDate = true;
  151. auto cb = ai->cb.get();
  152. auto mapSize = ai->cb->getMapSize();
  153. if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
  154. hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
  155. std::vector<std::unique_ptr<CGHeroInstance>> temporaryHeroes;
  156. std::map<const CGHeroInstance *, const CGTownInstance *> heroTownMap;
  157. std::map<const CGHeroInstance *, HeroRole> townHeroes;
  158. auto addTownHero = [&](const CGTownInstance * town)
  159. {
  160. auto townHero = temporaryHeroes.emplace_back(std::make_unique<CGHeroInstance>(town->cb)).get();
  161. CRandomGenerator rng;
  162. auto visitablePos = town->visitablePos();
  163. townHero->setOwner(ai->playerID); // lets avoid having multiple colors
  164. townHero->initHero(rng, static_cast<HeroTypeID>(0));
  165. townHero->pos = townHero->convertFromVisitablePos(visitablePos);
  166. townHero->initObj(rng);
  167. heroTownMap[townHero] = town;
  168. townHeroes[townHero] = HeroRole::MAIN;
  169. };
  170. for(auto obj : ai->memory->visitableObjs)
  171. {
  172. if(obj && obj->ID == Obj::TOWN)
  173. {
  174. addTownHero(dynamic_cast<const CGTownInstance *>(obj));
  175. }
  176. }
  177. for(auto town : cb->getTownsInfo())
  178. {
  179. addTownHero(town);
  180. }
  181. PathfinderSettings ps;
  182. ps.mainTurnDistanceLimit = ps.scoutTurnDistanceLimit = ai->settings->getMainHeroTurnDistanceLimit();
  183. ai->pathfinder->updatePaths(townHeroes, ps);
  184. pforeachTilePaths(mapSize, ai, [&](const int3 & pos, const std::vector<AIPath> & paths)
  185. {
  186. float ourDistance = std::numeric_limits<float>::max();
  187. float enemyDistance = std::numeric_limits<float>::max();
  188. const CGTownInstance * enemyTown = nullptr;
  189. const CGTownInstance * ourTown = nullptr;
  190. for(const AIPath & path : paths)
  191. {
  192. if(!path.targetHero || path.getFirstBlockedAction())
  193. continue;
  194. auto town = heroTownMap[path.targetHero];
  195. if(town->getOwner() == ai->playerID)
  196. {
  197. if(ourDistance > path.movementCost())
  198. {
  199. ourDistance = path.movementCost();
  200. ourTown = town;
  201. }
  202. }
  203. else
  204. {
  205. if(enemyDistance > path.movementCost())
  206. {
  207. enemyDistance = path.movementCost();
  208. enemyTown = town;
  209. }
  210. }
  211. }
  212. if(vstd::isAlmostEqual(ourDistance, enemyDistance))
  213. {
  214. hitMap[pos.x][pos.y][pos.z].closestTown = nullptr;
  215. }
  216. else if(!enemyTown || ourDistance < enemyDistance)
  217. {
  218. hitMap[pos.x][pos.y][pos.z].closestTown = ourTown;
  219. }
  220. else
  221. {
  222. hitMap[pos.x][pos.y][pos.z].closestTown = enemyTown;
  223. }
  224. });
  225. }
  226. const std::vector<HitMapInfo> & DangerHitMapAnalyzer::getTownThreats(const CGTownInstance * town) const
  227. {
  228. static const std::vector<HitMapInfo> empty = {};
  229. auto result = townThreats.find(town->id);
  230. return result == townThreats.end() ? empty : result->second;
  231. }
  232. PlayerColor DangerHitMapAnalyzer::getTileOwner(const int3 & tile) const
  233. {
  234. auto town = hitMap[tile.x][tile.y][tile.z].closestTown;
  235. return town ? town->getOwner() : PlayerColor::NEUTRAL;
  236. }
  237. const CGTownInstance * DangerHitMapAnalyzer::getClosestTown(const int3 & tile) const
  238. {
  239. return hitMap[tile.x][tile.y][tile.z].closestTown;
  240. }
  241. uint64_t DangerHitMapAnalyzer::enemyCanKillOurHeroesAlongThePath(const AIPath & path) const
  242. {
  243. int3 tile = path.targetTile();
  244. int turn = path.turn();
  245. const auto& info = getTileThreat(tile);
  246. return (info.fastestDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.fastestDanger.danger))
  247. || (info.maximumDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.maximumDanger.danger));
  248. }
  249. const HitMapNode & DangerHitMapAnalyzer::getObjectThreat(const CGObjectInstance * obj) const
  250. {
  251. auto tile = obj->visitablePos();
  252. return getTileThreat(tile);
  253. }
  254. const HitMapNode & DangerHitMapAnalyzer::getTileThreat(const int3 & tile) const
  255. {
  256. return hitMap[tile.x][tile.y][tile.z];
  257. }
  258. std::set<const CGObjectInstance *> DangerHitMapAnalyzer::getOneTurnAccessibleObjects(const CGHeroInstance * enemy) const
  259. {
  260. std::set<const CGObjectInstance *> result;
  261. for(auto & obj : enemyHeroAccessibleObjects)
  262. {
  263. if(obj.hero == enemy)
  264. result.insert(obj.obj);
  265. }
  266. return result;
  267. }
  268. void DangerHitMapAnalyzer::reset()
  269. {
  270. hitMapUpToDate = false;
  271. }
  272. }