DangerHitMapAnalyzer.cpp 9.4 KB

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