AINodeStorage.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * AINodeStorage.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 "AINodeStorage.h"
  12. #include "Actions/TownPortalAction.h"
  13. #include "../Goals/Goals.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/pathfinder/CPathfinder.h"
  18. #include "../../../lib/pathfinder/PathfinderOptions.h"
  19. #include "../../../lib/pathfinder/PathfinderUtil.h"
  20. #include "../../../lib/CPlayerState.h"
  21. AINodeStorage::AINodeStorage(const int3 & Sizes)
  22. : sizes(Sizes)
  23. {
  24. nodes.resize(boost::extents[EPathfindingLayer::NUM_LAYERS][sizes.z][sizes.x][sizes.y][NUM_CHAINS]);
  25. dangerEvaluator.reset(new FuzzyHelper());
  26. }
  27. AINodeStorage::~AINodeStorage() = default;
  28. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  29. {
  30. int3 pos;
  31. const int3 sizes = gs->getMapSize();
  32. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  33. const PlayerColor player = hero->tempOwner;
  34. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  35. const bool useFlying = options.useFlying;
  36. const bool useWaterWalking = options.useWaterWalking;
  37. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  38. {
  39. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  40. {
  41. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  42. {
  43. const TerrainTile & tile = gs->map->getTile(pos);
  44. if(!tile.terType->isPassable())
  45. continue;
  46. if(tile.terType->isWater())
  47. {
  48. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  49. if(useFlying)
  50. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  51. if(useWaterWalking)
  52. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  53. }
  54. else
  55. {
  56. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  57. if(useFlying)
  58. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  59. }
  60. }
  61. }
  62. }
  63. }
  64. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  65. {
  66. return static_cast<const AIPathNode *>(node);
  67. }
  68. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  69. {
  70. auto aiNode = static_cast<AIPathNode *>(node);
  71. updater(aiNode);
  72. }
  73. bool AINodeStorage::isBattleNode(const CGPathNode * node) const
  74. {
  75. return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0;
  76. }
  77. std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber)
  78. {
  79. auto chains = nodes[layer][pos.z][pos.x][pos.y];
  80. for(AIPathNode & node : chains)
  81. {
  82. if(node.chainMask == chainNumber)
  83. {
  84. return &node;
  85. }
  86. if(node.chainMask == 0)
  87. {
  88. node.chainMask = chainNumber;
  89. return &node;
  90. }
  91. }
  92. return std::nullopt;
  93. }
  94. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  95. {
  96. auto hpos = hero->visitablePos();
  97. auto initialNode = getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN).value();
  98. initialNode->turns = 0;
  99. initialNode->moveRemains = hero->movementPointsRemaining();
  100. initialNode->danger = 0;
  101. initialNode->setCost(0.0);
  102. return {initialNode};
  103. }
  104. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, EPathAccessibility accessibility)
  105. {
  106. for(int i = 0; i < NUM_CHAINS; i++)
  107. {
  108. AIPathNode & heroNode = nodes[layer][coord.z][coord.x][coord.y][i];
  109. heroNode.chainMask = 0;
  110. heroNode.danger = 0;
  111. heroNode.manaCost = 0;
  112. heroNode.specialAction.reset();
  113. heroNode.update(coord, layer, accessibility);
  114. }
  115. }
  116. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  117. {
  118. const AIPathNode * srcNode = getAINode(source.node);
  119. updateAINode(destination.node, [&](AIPathNode * dstNode)
  120. {
  121. dstNode->moveRemains = destination.movementLeft;
  122. dstNode->turns = destination.turn;
  123. dstNode->setCost(destination.cost);
  124. dstNode->danger = srcNode->danger;
  125. dstNode->action = destination.action;
  126. dstNode->theNodeBefore = srcNode->theNodeBefore;
  127. dstNode->manaCost = srcNode->manaCost;
  128. if(dstNode->specialAction)
  129. {
  130. dstNode->specialAction->applyOnDestination(getHero(), destination, source, dstNode, srcNode);
  131. }
  132. });
  133. }
  134. void AINodeStorage::calculateNeighbours(
  135. std::vector<CGPathNode *> & result,
  136. const PathNodeInfo & source,
  137. EPathfindingLayer layer,
  138. const PathfinderConfig * pathfinderConfig,
  139. const CPathfinderHelper * pathfinderHelper)
  140. {
  141. std::vector<int3> accessibleNeighbourTiles;
  142. result.clear();
  143. accessibleNeighbourTiles.reserve(8);
  144. pathfinderHelper->calculateNeighbourTiles(accessibleNeighbourTiles, source);
  145. const AIPathNode * srcNode = getAINode(source.node);
  146. for(auto & neighbour : accessibleNeighbourTiles)
  147. {
  148. for(EPathfindingLayer i = EPathfindingLayer::LAND; i < EPathfindingLayer::NUM_LAYERS; i.advance(1))
  149. {
  150. auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask);
  151. if(!nextNode || nextNode.value()->accessible == EPathAccessibility::NOT_SET)
  152. continue;
  153. result.push_back(nextNode.value());
  154. }
  155. }
  156. }
  157. void AINodeStorage::setHero(HeroPtr heroPtr, const VCAI * _ai)
  158. {
  159. hero = heroPtr.get();
  160. cb = _ai->myCb.get();
  161. ai = _ai;
  162. }
  163. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  164. const PathNodeInfo & source,
  165. const PathfinderConfig * pathfinderConfig,
  166. const CPathfinderHelper * pathfinderHelper)
  167. {
  168. std::vector<CGPathNode *> neighbours;
  169. if(source.isNodeObjectVisitable())
  170. {
  171. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  172. auto srcNode = getAINode(source.node);
  173. for(auto & neighbour : accessibleExits)
  174. {
  175. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->chainMask);
  176. if(!node)
  177. continue;
  178. neighbours.push_back(node.value());
  179. }
  180. }
  181. if(hero->visitablePos() == source.coord)
  182. {
  183. calculateTownPortalTeleportations(source, neighbours);
  184. }
  185. return neighbours;
  186. }
  187. void AINodeStorage::calculateTownPortalTeleportations(
  188. const PathNodeInfo & source,
  189. std::vector<CGPathNode *> & neighbours)
  190. {
  191. SpellID spellID = SpellID::TOWN_PORTAL;
  192. const CSpell * townPortal = spellID.toSpell();
  193. auto srcNode = getAINode(source.node);
  194. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  195. {
  196. auto towns = cb->getTownsInfo(false);
  197. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  198. {
  199. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  200. });
  201. if(!towns.size())
  202. {
  203. return;
  204. }
  205. // TODO: Copy/Paste from TownPortalMechanics
  206. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  207. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  208. if(hero->movementPointsRemaining() < movementCost)
  209. {
  210. return;
  211. }
  212. if(skillLevel < MasteryLevel::ADVANCED)
  213. {
  214. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  215. {
  216. return hero->visitablePos().dist2dSQ(t->visitablePos());
  217. });
  218. towns = std::vector<const CGTownInstance *>{ nearestTown };
  219. }
  220. for(const CGTownInstance * targetTown : towns)
  221. {
  222. if(targetTown->visitingHero)
  223. continue;
  224. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->chainMask | CAST_CHAIN);
  225. if(nodeOptional)
  226. {
  227. #ifdef VCMI_TRACE_PATHFINDER
  228. logAi->trace("Adding town portal node at %s", targetTown->name);
  229. #endif
  230. AIPathNode * node = nodeOptional.value();
  231. node->theNodeBefore = source.node;
  232. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  233. node->moveRemains = source.node->moveRemains;
  234. neighbours.push_back(node);
  235. }
  236. }
  237. }
  238. }
  239. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  240. {
  241. auto pos = destination.coord;
  242. auto chains = nodes[EPathfindingLayer::LAND][pos.z][pos.x][pos.y];
  243. auto destinationNode = getAINode(destination.node);
  244. for(const AIPathNode & node : chains)
  245. {
  246. auto sameNode = node.chainMask == destinationNode->chainMask;
  247. if(sameNode || node.action == EPathNodeAction::UNKNOWN)
  248. {
  249. continue;
  250. }
  251. if(node.danger <= destinationNode->danger && destinationNode->chainMask == 1 && node.chainMask == 0)
  252. {
  253. if(node.getCost() < destinationNode->getCost())
  254. {
  255. #ifdef VCMI_TRACE_PATHFINDER
  256. logAi->trace(
  257. "Block inefficient move %s:->%s, mask=%i, mp diff: %i",
  258. source.coord.toString(),
  259. destination.coord.toString(),
  260. destinationNode->chainMask,
  261. node.moveRemains - destinationNode->moveRemains);
  262. #endif
  263. return true;
  264. }
  265. }
  266. }
  267. return false;
  268. }
  269. bool AINodeStorage::isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const
  270. {
  271. return nodes[layer][pos.z][pos.x][pos.y][0].action != EPathNodeAction::UNKNOWN;
  272. }
  273. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  274. {
  275. std::vector<AIPath> paths;
  276. auto chains = nodes[isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL][pos.z][pos.x][pos.y];
  277. auto initialPos = hero->visitablePos();
  278. for(const AIPathNode & node : chains)
  279. {
  280. if(node.action == EPathNodeAction::UNKNOWN)
  281. {
  282. continue;
  283. }
  284. AIPath path;
  285. const AIPathNode * current = &node;
  286. while(current != nullptr && current->coord != initialPos)
  287. {
  288. AIPathNodeInfo pathNode;
  289. pathNode.cost = current->getCost();
  290. pathNode.turns = current->turns;
  291. pathNode.danger = current->danger;
  292. pathNode.coord = current->coord;
  293. path.nodes.push_back(pathNode);
  294. path.specialAction = current->specialAction;
  295. current = getAINode(current->theNodeBefore);
  296. }
  297. path.targetObjectDanger = evaluateDanger(pos);
  298. paths.push_back(path);
  299. }
  300. return paths;
  301. }
  302. AIPath::AIPath()
  303. : nodes({})
  304. {
  305. }
  306. int3 AIPath::firstTileToGet() const
  307. {
  308. if(nodes.size())
  309. {
  310. return nodes.back().coord;
  311. }
  312. return int3(-1, -1, -1);
  313. }
  314. uint64_t AIPath::getPathDanger() const
  315. {
  316. if(nodes.size())
  317. {
  318. return nodes.front().danger;
  319. }
  320. return 0;
  321. }
  322. float AIPath::movementCost() const
  323. {
  324. if(nodes.size())
  325. {
  326. return nodes.front().cost;
  327. }
  328. // TODO: boost:optional?
  329. return 0.0;
  330. }
  331. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  332. {
  333. uint64_t pathDanger = getPathDanger();
  334. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  335. return danger;
  336. }