AINodeStorage.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. if(heroChainPass)
  29. return;
  30. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  31. int3 pos;
  32. const PlayerColor player = ai->playerID;
  33. const int3 sizes = gs->getMapSize();
  34. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  35. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  36. const bool useFlying = options.useFlying;
  37. const bool useWaterWalking = options.useWaterWalking;
  38. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  39. {
  40. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  41. {
  42. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  43. {
  44. const TerrainTile * tile = &gs->map->getTile(pos);
  45. switch(tile->terType)
  46. {
  47. case ETerrainType::ROCK:
  48. break;
  49. case ETerrainType::WATER:
  50. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  51. if(useFlying)
  52. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  53. if(useWaterWalking)
  54. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  55. break;
  56. default:
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. void AINodeStorage::clear()
  67. {
  68. actors.clear();
  69. heroChainPass = false;
  70. }
  71. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  72. {
  73. return static_cast<const AIPathNode *>(node);
  74. }
  75. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  76. {
  77. auto aiNode = static_cast<AIPathNode *>(node);
  78. updater(aiNode);
  79. }
  80. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  81. const int3 & pos,
  82. const EPathfindingLayer layer,
  83. const ChainActor * actor)
  84. {
  85. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  86. for(AIPathNode & node : chains)
  87. {
  88. if(node.actor == actor)
  89. {
  90. return &node;
  91. }
  92. if(!node.actor)
  93. {
  94. node.actor = actor;
  95. return &node;
  96. }
  97. }
  98. return boost::none;
  99. }
  100. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  101. {
  102. if(heroChainPass)
  103. return heroChain;
  104. std::vector<CGPathNode *> initialNodes;
  105. for(auto actorPtr : actors)
  106. {
  107. ChainActor * actor = actorPtr.get();
  108. AIPathNode * initialNode =
  109. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  110. .get();
  111. initialNode->turns = actor->initialTurn;
  112. initialNode->moveRemains = actor->initialMovement;
  113. initialNode->danger = 0;
  114. initialNode->cost = actor->initialTurn;
  115. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  116. if(actor->isMovable)
  117. {
  118. initialNodes.push_back(initialNode);
  119. }
  120. else
  121. {
  122. initialNode->locked = true;
  123. }
  124. }
  125. return initialNodes;
  126. }
  127. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  128. {
  129. for(int i = 0; i < NUM_CHAINS; i++)
  130. {
  131. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  132. heroNode.actor = nullptr;
  133. heroNode.danger = 0;
  134. heroNode.manaCost = 0;
  135. heroNode.specialAction.reset();
  136. heroNode.armyLoss = 0;
  137. heroNode.chainOther = nullptr;
  138. heroNode.update(coord, layer, accessibility);
  139. }
  140. }
  141. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  142. {
  143. const AIPathNode * srcNode = getAINode(source.node);
  144. updateAINode(destination.node, [&](AIPathNode * dstNode)
  145. {
  146. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  147. if(srcNode->specialAction || srcNode->chainOther)
  148. {
  149. // there is some action on source tile which should be performed before we can bypass it
  150. destination.node->theNodeBefore = source.node;
  151. }
  152. if(dstNode->specialAction && dstNode->actor)
  153. {
  154. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  155. }
  156. #ifdef VCMI_TRACE_PATHFINDER_EX
  157. logAi->trace(
  158. "Commited %s -> %s, cost: %f, hero: %s, mask: %i",
  159. source.coord.toString(),
  160. destination.coord.toString(),
  161. destination.cost,
  162. dstNode->actor->toString(),
  163. dstNode->actor->chainMask);
  164. #endif
  165. });
  166. }
  167. void AINodeStorage::commit(
  168. AIPathNode * destination,
  169. const AIPathNode * source,
  170. CGPathNode::ENodeAction action,
  171. int turn,
  172. int movementLeft,
  173. float cost) const
  174. {
  175. destination->action = action;
  176. destination->cost = cost;
  177. destination->moveRemains = movementLeft;
  178. destination->turns = turn;
  179. destination->armyLoss = source->armyLoss;
  180. destination->manaCost = source->manaCost;
  181. destination->danger = source->danger;
  182. destination->theNodeBefore = source->theNodeBefore;
  183. destination->chainOther = nullptr;
  184. }
  185. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  186. const PathNodeInfo & source,
  187. const PathfinderConfig * pathfinderConfig,
  188. const CPathfinderHelper * pathfinderHelper)
  189. {
  190. std::vector<CGPathNode *> neighbours;
  191. neighbours.reserve(16);
  192. const AIPathNode * srcNode = getAINode(source.node);
  193. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  194. for(auto & neighbour : accessibleNeighbourTiles)
  195. {
  196. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  197. {
  198. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  199. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  200. continue;
  201. neighbours.push_back(nextNode.get());
  202. }
  203. }
  204. return neighbours;
  205. }
  206. bool AINodeStorage::calculateHeroChain()
  207. {
  208. heroChainPass = true;
  209. heroChain.resize(0);
  210. std::vector<AIPathNode *> existingChains;
  211. std::vector<ExchangeCandidate> newChains;
  212. existingChains.reserve(NUM_CHAINS);
  213. newChains.reserve(NUM_CHAINS);
  214. foreach_tile_pos([&](const int3 & pos) {
  215. auto layer = EPathfindingLayer::LAND;
  216. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  217. existingChains.resize(0);
  218. newChains.resize(0);
  219. for(AIPathNode & node : chains)
  220. {
  221. if(node.coord.x == 60 && node.coord.y == 56 && node.actor)
  222. logAi->trace(node.actor->toString());
  223. if(node.turns <= heroChainMaxTurns && node.action != CGPathNode::ENodeAction::UNKNOWN)
  224. existingChains.push_back(&node);
  225. }
  226. for(AIPathNode * node : existingChains)
  227. {
  228. if(node->actor->hero)
  229. {
  230. calculateHeroChain(node, existingChains, newChains);
  231. }
  232. }
  233. cleanupInefectiveChains(newChains);
  234. addHeroChain(newChains);
  235. });
  236. return heroChain.size();
  237. }
  238. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  239. {
  240. vstd::erase_if(result, [&](ExchangeCandidate & chainInfo) -> bool
  241. {
  242. auto pos = chainInfo.coord;
  243. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  244. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  245. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  246. });
  247. }
  248. void AINodeStorage::calculateHeroChain(
  249. AIPathNode * srcNode,
  250. const std::vector<AIPathNode *> & variants,
  251. std::vector<ExchangeCandidate> & result) const
  252. {
  253. for(AIPathNode * node : variants)
  254. {
  255. if(node == srcNode || !node->actor || node->turns > heroChainMaxTurns
  256. || node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  257. {
  258. continue;
  259. }
  260. #ifdef VCMI_TRACE_PATHFINDER_EX
  261. logAi->trace(
  262. "Thy exchange %s[%i] -> %s[%i] at %s",
  263. node->actor->toString(),
  264. node->actor->chainMask,
  265. srcNode->actor->toString(),
  266. srcNode->actor->chainMask,
  267. srcNode->coord.toString());
  268. #endif
  269. calculateHeroChain(srcNode, node, result);
  270. }
  271. }
  272. void AINodeStorage::calculateHeroChain(
  273. AIPathNode * carrier,
  274. AIPathNode * other,
  275. std::vector<ExchangeCandidate> & result) const
  276. {
  277. if(!carrier->actor->isMovable)
  278. return;
  279. if(carrier->actor->canExchange(other->actor))
  280. {
  281. #ifdef VCMI_TRACE_PATHFINDER_EX
  282. logAi->trace(
  283. "Exchange allowed %s[%i] -> %s[%i] at %s",
  284. other->actor->toString(),
  285. other->actor->chainMask,
  286. carrier->actor->toString(),
  287. carrier->actor->chainMask,
  288. carrier->coord.toString());
  289. #endif
  290. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  291. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  292. if(hasLessMp && hasLessExperience)
  293. {
  294. #ifdef VCMI_TRACE_PATHFINDER_EX
  295. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  296. #endif
  297. return;
  298. }
  299. auto newActor = carrier->actor->exchange(other->actor);
  300. result.push_back(calculateExchange(newActor, carrier, other));
  301. }
  302. }
  303. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  304. {
  305. for(const ExchangeCandidate & chainInfo : result)
  306. {
  307. auto carrier = chainInfo.carrierParent;
  308. auto newActor = chainInfo.actor;
  309. auto other = chainInfo.otherParent;
  310. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  311. if(!chainNodeOptional)
  312. {
  313. #ifdef VCMI_TRACE_PATHFINDER_EX
  314. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  315. #endif
  316. continue;
  317. }
  318. auto exchangeNode = chainNodeOptional.get();
  319. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  320. {
  321. #ifdef VCMI_TRACE_PATHFINDER_EX
  322. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  323. #endif
  324. continue;
  325. }
  326. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  327. {
  328. #ifdef VCMI_TRACE_PATHFINDER_EX
  329. logAi->trace(
  330. "Exchange at %s is is not effective enough. %f < %f",
  331. exchangeNode->coord.toString(),
  332. exchangeNode->cost,
  333. chainInfo.cost);
  334. #endif
  335. continue;
  336. }
  337. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  338. exchangeNode->chainOther = other;
  339. exchangeNode->armyLoss = chainInfo.armyLoss;
  340. #ifdef VCMI_TRACE_PATHFINDER_EX
  341. logAi->trace(
  342. "Chain accepted at %s %s -> %s, mask %i, cost %f",
  343. exchangeNode->coord.toString(),
  344. other->actor->toString(),
  345. exchangeNode->actor->toString(),
  346. exchangeNode->actor->chainMask,
  347. exchangeNode->cost);
  348. #endif
  349. heroChain.push_back(exchangeNode);
  350. }
  351. }
  352. ExchangeCandidate AINodeStorage::calculateExchange(
  353. ChainActor * exchangeActor,
  354. AIPathNode * carrierParentNode,
  355. AIPathNode * otherParentNode) const
  356. {
  357. ExchangeCandidate candidate;
  358. auto carrierActor = carrierParentNode->actor;
  359. auto otherActor = otherParentNode->actor;
  360. candidate.layer = carrierParentNode->layer;
  361. candidate.coord = carrierParentNode->coord;
  362. candidate.carrierParent = carrierParentNode;
  363. candidate.otherParent = otherParentNode;
  364. candidate.actor = exchangeActor;
  365. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  366. candidate.turns = carrierParentNode->turns;
  367. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  368. candidate.moveRemains = carrierParentNode->moveRemains;
  369. if(carrierParentNode->turns < otherParentNode->turns)
  370. {
  371. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  372. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  373. + carrierParentNode->moveRemains / (float)moveRemains;
  374. candidate.turns = otherParentNode->turns;
  375. candidate.cost += waitingCost;
  376. candidate.moveRemains = moveRemains;
  377. }
  378. return candidate;
  379. }
  380. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  381. {
  382. auto aiNode = getAINode(node);
  383. return aiNode->actor->hero;
  384. }
  385. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  386. {
  387. std::set<const CGHeroInstance *> heroes;
  388. for(auto actor : actors)
  389. {
  390. if(actor->hero)
  391. heroes.insert(actor->hero);
  392. }
  393. return heroes;
  394. }
  395. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  396. {
  397. cb = _ai->myCb.get();
  398. ai = _ai;
  399. for(auto & hero : heroes)
  400. {
  401. uint64_t mask = 1 << actors.size();
  402. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask, ai));
  403. }
  404. }
  405. void AINodeStorage::setTownsAndDwellings(
  406. const std::vector<const CGTownInstance *> & towns,
  407. const std::set<const CGObjectInstance *> & visitableObjs)
  408. {
  409. for(auto town : towns)
  410. {
  411. uint64_t mask = 1 << actors.size();
  412. if(town->getUpperArmy()->getArmyStrength())
  413. {
  414. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  415. }
  416. }
  417. auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  418. auto waitForGrowth = dayOfWeek > 4;
  419. for(auto obj: visitableObjs)
  420. {
  421. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  422. if(dwelling)
  423. {
  424. uint64_t mask = 1 << actors.size();
  425. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  426. if(dwellingActor->creatureSet->getArmyStrength())
  427. {
  428. actors.push_back(dwellingActor);
  429. }
  430. if(waitForGrowth)
  431. {
  432. mask = 1 << actors.size();
  433. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  434. if(dwellingActor->creatureSet->getArmyStrength())
  435. {
  436. actors.push_back(dwellingActor);
  437. }
  438. }
  439. }
  440. }
  441. }
  442. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  443. const PathNodeInfo & source,
  444. const PathfinderConfig * pathfinderConfig,
  445. const CPathfinderHelper * pathfinderHelper)
  446. {
  447. std::vector<CGPathNode *> neighbours;
  448. if(source.isNodeObjectVisitable())
  449. {
  450. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  451. auto srcNode = getAINode(source.node);
  452. for(auto & neighbour : accessibleExits)
  453. {
  454. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  455. if(!node)
  456. continue;
  457. neighbours.push_back(node.get());
  458. }
  459. }
  460. if(source.isInitialPosition)
  461. {
  462. calculateTownPortalTeleportations(source, neighbours);
  463. }
  464. return neighbours;
  465. }
  466. void AINodeStorage::calculateTownPortalTeleportations(
  467. const PathNodeInfo & source,
  468. std::vector<CGPathNode *> & neighbours)
  469. {
  470. SpellID spellID = SpellID::TOWN_PORTAL;
  471. const CSpell * townPortal = spellID.toSpell();
  472. auto srcNode = getAINode(source.node);
  473. auto hero = srcNode->actor->hero;
  474. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  475. {
  476. auto towns = cb->getTownsInfo(false);
  477. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  478. {
  479. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  480. });
  481. if(!towns.size())
  482. {
  483. return;
  484. }
  485. // TODO: Copy/Paste from TownPortalMechanics
  486. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  487. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  488. if(hero->movement < movementCost)
  489. {
  490. return;
  491. }
  492. if(skillLevel < SecSkillLevel::ADVANCED)
  493. {
  494. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  495. {
  496. return hero->visitablePos().dist2dSQ(t->visitablePos());
  497. });
  498. towns = std::vector<const CGTownInstance *>{ nearestTown };
  499. }
  500. for(const CGTownInstance * targetTown : towns)
  501. {
  502. if(targetTown->visitingHero)
  503. continue;
  504. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  505. if(nodeOptional)
  506. {
  507. #ifdef VCMI_TRACE_PATHFINDER
  508. logAi->trace("Adding town portal node at %s", targetTown->name);
  509. #endif
  510. AIPathNode * node = nodeOptional.get();
  511. node->theNodeBefore = source.node;
  512. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  513. node->moveRemains = source.node->moveRemains;
  514. neighbours.push_back(node);
  515. }
  516. }
  517. }
  518. }
  519. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  520. {
  521. auto pos = destination.coord;
  522. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  523. return hasBetterChain(source.node, getAINode(destination.node), chains);
  524. }
  525. template<class NodeRange>
  526. bool AINodeStorage::hasBetterChain(
  527. const CGPathNode * source,
  528. const AIPathNode * destinationNode,
  529. const NodeRange & chains) const
  530. {
  531. auto dstActor = destinationNode->actor;
  532. for(const AIPathNode & node : chains)
  533. {
  534. auto sameNode = node.actor == destinationNode->actor;
  535. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  536. {
  537. continue;
  538. }
  539. if(node.danger <= destinationNode->danger && destinationNode->actor == node.actor->battleActor)
  540. {
  541. if(node.cost < destinationNode->cost)
  542. {
  543. #ifdef VCMI_TRACE_PATHFINDER
  544. logAi->trace(
  545. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  546. source->coord.toString(),
  547. destinationNode->coord.toString(),
  548. destinationNode->actor->chainMask,
  549. node.moveRemains - destinationNode->moveRemains);
  550. #endif
  551. return true;
  552. }
  553. }
  554. if(dstActor->actorExchangeCount == 1)
  555. continue;
  556. auto nodeActor = node.actor;
  557. if(nodeActor->armyValue - node.armyLoss >= dstActor->armyValue - destinationNode->armyLoss
  558. && nodeActor->heroFightingStrength >= dstActor->heroFightingStrength
  559. && node.cost >= destinationNode->cost)
  560. {
  561. return true;
  562. }
  563. }
  564. return false;
  565. }
  566. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  567. {
  568. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  569. for(const AIPathNode & node : chains)
  570. {
  571. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  572. && node.actor && node.actor->hero == hero.h)
  573. {
  574. return true;
  575. }
  576. }
  577. return false;
  578. }
  579. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  580. {
  581. std::vector<AIPath> paths;
  582. paths.reserve(NUM_CHAINS / 4);
  583. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  584. for(const AIPathNode & node : chains)
  585. {
  586. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  587. {
  588. continue;
  589. }
  590. AIPath path;
  591. path.targetHero = node.actor->hero;
  592. path.heroArmy = node.actor->creatureSet;
  593. path.armyLoss = node.armyLoss;
  594. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  595. path.chainMask = node.actor->chainMask;
  596. fillChainInfo(&node, path);
  597. paths.push_back(path);
  598. }
  599. return paths;
  600. }
  601. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path) const
  602. {
  603. while(node != nullptr)
  604. {
  605. if(!node->actor->hero)
  606. return;
  607. if(node->chainOther)
  608. fillChainInfo(node->chainOther, path);
  609. if(node->actor->hero->visitablePos() != node->coord)
  610. {
  611. AIPathNodeInfo pathNode;
  612. pathNode.cost = node->cost;
  613. pathNode.targetHero = node->actor->hero;
  614. pathNode.turns = node->turns;
  615. pathNode.danger = node->danger;
  616. pathNode.coord = node->coord;
  617. path.nodes.push_back(pathNode);
  618. }
  619. path.specialAction = node->specialAction;
  620. node = getAINode(node->theNodeBefore);
  621. }
  622. }
  623. AIPath::AIPath()
  624. : nodes({})
  625. {
  626. }
  627. int3 AIPath::firstTileToGet() const
  628. {
  629. if(nodes.size())
  630. {
  631. return nodes.back().coord;
  632. }
  633. return int3(-1, -1, -1);
  634. }
  635. const AIPathNodeInfo & AIPath::firstNode() const
  636. {
  637. return nodes.back();
  638. }
  639. uint64_t AIPath::getPathDanger() const
  640. {
  641. if(nodes.size())
  642. {
  643. return nodes.front().danger;
  644. }
  645. return 0;
  646. }
  647. float AIPath::movementCost() const
  648. {
  649. if(nodes.size())
  650. {
  651. return nodes.front().cost;
  652. }
  653. // TODO: boost:optional?
  654. return 0.0;
  655. }
  656. uint64_t AIPath::getHeroStrength() const
  657. {
  658. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  659. }
  660. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  661. {
  662. uint64_t pathDanger = getPathDanger();
  663. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  664. return danger;
  665. }