DangerHitMapAnalyzer.cpp 9.7 KB

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