AINodeStorage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]);
  23. dangerEvaluator.reset(new FuzzyHelper());
  24. }
  25. AINodeStorage::~AINodeStorage() = default;
  26. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const PlayerColor player = ai->playerID;
  31. const int3 sizes = gs->getMapSize();
  32. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  33. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  34. const bool useFlying = options.useFlying;
  35. const bool useWaterWalking = options.useWaterWalking;
  36. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. switch(tile->terType)
  44. {
  45. case ETerrainType::ROCK:
  46. break;
  47. case ETerrainType::WATER:
  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. break;
  54. default:
  55. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  56. if(useFlying)
  57. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  58. break;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. void AINodeStorage::clear()
  65. {
  66. actors.clear();
  67. }
  68. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  69. {
  70. return static_cast<const AIPathNode *>(node);
  71. }
  72. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  73. {
  74. auto aiNode = static_cast<AIPathNode *>(node);
  75. updater(aiNode);
  76. }
  77. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  78. const int3 & pos,
  79. const EPathfindingLayer layer,
  80. const ChainActor * actor)
  81. {
  82. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  83. for(AIPathNode & node : chains)
  84. {
  85. if(node.actor == actor)
  86. {
  87. return &node;
  88. }
  89. if(!node.actor)
  90. {
  91. node.actor = actor;
  92. return &node;
  93. }
  94. }
  95. return boost::none;
  96. }
  97. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  98. {
  99. std::vector<CGPathNode *> initialNodes;
  100. for(auto actorPtr : actors)
  101. {
  102. ChainActor * actor = actorPtr.get();
  103. AIPathNode * initialNode =
  104. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  105. .get();
  106. initialNode->turns = actor->initialTurn;
  107. initialNode->moveRemains = actor->initialMovement;
  108. initialNode->danger = 0;
  109. initialNode->cost = 0.0;
  110. if(actor->isMovable)
  111. {
  112. initialNodes.push_back(initialNode);
  113. }
  114. else
  115. {
  116. initialNode->locked = true;
  117. }
  118. }
  119. return initialNodes;
  120. }
  121. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  122. {
  123. for(int i = 0; i < NUM_CHAINS; i++)
  124. {
  125. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  126. heroNode.actor = nullptr;
  127. heroNode.danger = 0;
  128. heroNode.manaCost = 0;
  129. heroNode.specialAction.reset();
  130. heroNode.armyLoss = 0;
  131. heroNode.update(coord, layer, accessibility);
  132. }
  133. }
  134. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  135. {
  136. const AIPathNode * srcNode = getAINode(source.node);
  137. updateAINode(destination.node, [&](AIPathNode * dstNode)
  138. {
  139. dstNode->moveRemains = destination.movementLeft;
  140. dstNode->turns = destination.turn;
  141. dstNode->cost = destination.cost;
  142. dstNode->danger = srcNode->danger;
  143. dstNode->action = destination.action;
  144. dstNode->theNodeBefore = srcNode->theNodeBefore;
  145. dstNode->manaCost = srcNode->manaCost;
  146. dstNode->armyLoss = srcNode->armyLoss;
  147. if(dstNode->specialAction && dstNode->actor)
  148. {
  149. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  150. }
  151. });
  152. }
  153. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  154. const PathNodeInfo & source,
  155. const PathfinderConfig * pathfinderConfig,
  156. const CPathfinderHelper * pathfinderHelper)
  157. {
  158. std::vector<CGPathNode *> neighbours;
  159. neighbours.reserve(16);
  160. const AIPathNode * srcNode = getAINode(source.node);
  161. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  162. for(auto & neighbour : accessibleNeighbourTiles)
  163. {
  164. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  165. {
  166. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  167. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  168. continue;
  169. neighbours.push_back(nextNode.get());
  170. }
  171. }
  172. if((source.node->layer == EPathfindingLayer::LAND || source.node->layer == EPathfindingLayer::SAIL)
  173. && source.node->turns < 1)
  174. {
  175. addHeroChain(neighbours, srcNode);
  176. }
  177. return neighbours;
  178. }
  179. void AINodeStorage::addHeroChain(std::vector<CGPathNode *> & result, const AIPathNode * srcNode)
  180. {
  181. auto chains = nodes[srcNode->coord.x][srcNode->coord.y][srcNode->coord.z][srcNode->layer];
  182. for(const AIPathNode & node : chains)
  183. {
  184. if(!node.locked || !node.actor || node.action == CGPathNode::ENodeAction::UNKNOWN && node.actor->hero)
  185. {
  186. continue;
  187. }
  188. addHeroChain(result, srcNode, &node);
  189. addHeroChain(result, &node, srcNode);
  190. }
  191. }
  192. void AINodeStorage::addHeroChain(
  193. std::vector<CGPathNode *> & result,
  194. const AIPathNode * carrier,
  195. const AIPathNode * other)
  196. {
  197. if(carrier->actor->canExchange(other->actor))
  198. {
  199. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  200. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  201. if(hasLessMp && hasLessExperience)
  202. return;
  203. auto newActor = carrier->actor->exchange(other->actor);
  204. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  205. if(!chainNodeOptional)
  206. return;
  207. auto chainNode = chainNodeOptional.get();
  208. if(chainNode->locked)
  209. return;
  210. chainNode->specialAction = newActor->getExchangeAction();
  211. result.push_back(chainNode);
  212. }
  213. }
  214. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  215. {
  216. auto aiNode = getAINode(node);
  217. return aiNode->actor->hero;
  218. }
  219. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  220. {
  221. std::set<const CGHeroInstance *> heroes;
  222. for(auto actor : actors)
  223. {
  224. if(actor->hero)
  225. heroes.insert(actor->hero);
  226. }
  227. return heroes;
  228. }
  229. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  230. {
  231. cb = _ai->myCb.get();
  232. ai = _ai;
  233. for(auto & hero : heroes)
  234. {
  235. uint64_t mask = 1 << actors.size();
  236. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask));
  237. }
  238. }
  239. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  240. const PathNodeInfo & source,
  241. const PathfinderConfig * pathfinderConfig,
  242. const CPathfinderHelper * pathfinderHelper)
  243. {
  244. std::vector<CGPathNode *> neighbours;
  245. if(source.isNodeObjectVisitable())
  246. {
  247. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  248. auto srcNode = getAINode(source.node);
  249. for(auto & neighbour : accessibleExits)
  250. {
  251. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  252. if(!node)
  253. continue;
  254. neighbours.push_back(node.get());
  255. }
  256. }
  257. if(source.isInitialPosition)
  258. {
  259. calculateTownPortalTeleportations(source, neighbours);
  260. }
  261. return neighbours;
  262. }
  263. void AINodeStorage::calculateTownPortalTeleportations(
  264. const PathNodeInfo & source,
  265. std::vector<CGPathNode *> & neighbours)
  266. {
  267. SpellID spellID = SpellID::TOWN_PORTAL;
  268. const CSpell * townPortal = spellID.toSpell();
  269. auto srcNode = getAINode(source.node);
  270. auto hero = srcNode->actor->hero;
  271. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  272. {
  273. auto towns = cb->getTownsInfo(false);
  274. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  275. {
  276. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  277. });
  278. if(!towns.size())
  279. {
  280. return;
  281. }
  282. // TODO: Copy/Paste from TownPortalMechanics
  283. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  284. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  285. if(hero->movement < movementCost)
  286. {
  287. return;
  288. }
  289. if(skillLevel < SecSkillLevel::ADVANCED)
  290. {
  291. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  292. {
  293. return hero->visitablePos().dist2dSQ(t->visitablePos());
  294. });
  295. towns = std::vector<const CGTownInstance *>{ nearestTown };
  296. }
  297. for(const CGTownInstance * targetTown : towns)
  298. {
  299. if(targetTown->visitingHero)
  300. continue;
  301. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  302. if(nodeOptional)
  303. {
  304. #ifdef VCMI_TRACE_PATHFINDER
  305. logAi->trace("Adding town portal node at %s", targetTown->name);
  306. #endif
  307. AIPathNode * node = nodeOptional.get();
  308. node->theNodeBefore = source.node;
  309. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  310. node->moveRemains = source.node->moveRemains;
  311. neighbours.push_back(node);
  312. }
  313. }
  314. }
  315. }
  316. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  317. {
  318. auto pos = destination.coord;
  319. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  320. auto destinationNode = getAINode(destination.node);
  321. for(const AIPathNode & node : chains)
  322. {
  323. auto sameNode = node.actor == destinationNode->actor;
  324. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN)
  325. {
  326. continue;
  327. }
  328. if(node.danger <= destinationNode->danger && destinationNode->actor == node.actor->battleActor)
  329. {
  330. if(node.cost < destinationNode->cost)
  331. {
  332. #ifdef VCMI_TRACE_PATHFINDER
  333. logAi->trace(
  334. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  335. source.coord.toString(),
  336. destination.coord.toString(),
  337. destinationNode->actor->chainMask,
  338. node.moveRemains - destinationNode->moveRemains);
  339. #endif
  340. return true;
  341. }
  342. }
  343. }
  344. return false;
  345. }
  346. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  347. {
  348. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  349. for(const AIPathNode & node : chains)
  350. {
  351. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  352. && node.actor && node.actor->hero == hero.h)
  353. {
  354. return true;
  355. }
  356. }
  357. return false;
  358. }
  359. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  360. {
  361. std::vector<AIPath> paths;
  362. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  363. for(const AIPathNode & node : chains)
  364. {
  365. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  366. {
  367. continue;
  368. }
  369. AIPath path;
  370. const AIPathNode * current = &node;
  371. path.targetHero = node.actor->hero;
  372. auto initialPos = path.targetHero->visitablePos();
  373. while(current != nullptr && current->coord != initialPos)
  374. {
  375. AIPathNodeInfo pathNode;
  376. pathNode.cost = current->cost;
  377. pathNode.turns = current->turns;
  378. pathNode.danger = current->danger;
  379. pathNode.coord = current->coord;
  380. path.nodes.push_back(pathNode);
  381. path.specialAction = current->specialAction;
  382. current = getAINode(current->theNodeBefore);
  383. }
  384. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  385. paths.push_back(path);
  386. }
  387. return paths;
  388. }
  389. AIPath::AIPath()
  390. : nodes({})
  391. {
  392. }
  393. int3 AIPath::firstTileToGet() const
  394. {
  395. if(nodes.size())
  396. {
  397. return nodes.back().coord;
  398. }
  399. return int3(-1, -1, -1);
  400. }
  401. uint64_t AIPath::getPathDanger() const
  402. {
  403. if(nodes.size())
  404. {
  405. return nodes.front().danger;
  406. }
  407. return 0;
  408. }
  409. float AIPath::movementCost() const
  410. {
  411. if(nodes.size())
  412. {
  413. return nodes.front().cost;
  414. }
  415. // TODO: boost:optional?
  416. return 0.0;
  417. }
  418. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  419. {
  420. uint64_t pathDanger = getPathDanger();
  421. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  422. return danger;
  423. }