AINodeStorage.cpp 11 KB

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