AINodeStorage.cpp 10 KB

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