AINodeStorage.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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 <tbb/tbb.h>
  12. #include "AINodeStorage.h"
  13. #include "Actions/TownPortalAction.h"
  14. #include "../Goals/Goals.h"
  15. #include "../VCAI.h"
  16. #include "../Engine/Nullkiller.h"
  17. #include "../../../CCallback.h"
  18. #include "../../../lib/mapping/CMap.h"
  19. #include "../../../lib/mapObjects/MapObjects.h"
  20. #include "../../../lib/PathfinderUtil.h"
  21. #include "../../../lib/CPlayerState.h"
  22. using namespace tbb;
  23. std::shared_ptr<boost::multi_array<AIPathNode, 5>> AISharedStorage::shared;
  24. std::set<int3> commitedTiles;
  25. std::set<int3> commitedTilesInitial;
  26. const uint64_t FirstActorMask = 1;
  27. const int BUCKET_COUNT = 11;
  28. const int BUCKET_SIZE = GameConstants::MAX_HEROES_PER_PLAYER;
  29. const int NUM_CHAINS = BUCKET_COUNT * BUCKET_SIZE;
  30. const uint64_t MIN_ARMY_STRENGTH_FOR_CHAIN = 5000;
  31. const uint64_t MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR = 1000;
  32. AISharedStorage::AISharedStorage(int3 sizes)
  33. {
  34. if(!shared){
  35. shared.reset(new boost::multi_array<AIPathNode, 5>(
  36. boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]));
  37. }
  38. nodes = shared;
  39. }
  40. AISharedStorage::~AISharedStorage()
  41. {
  42. nodes.reset();
  43. if(shared && shared.use_count() == 1)
  44. {
  45. shared.reset();
  46. }
  47. }
  48. AINodeStorage::AINodeStorage(const Nullkiller * ai, const int3 & Sizes)
  49. : sizes(Sizes), ai(ai), cb(ai->cb.get()), nodes(Sizes)
  50. {
  51. dangerEvaluator.reset(new FuzzyHelper(ai));
  52. }
  53. AINodeStorage::~AINodeStorage() = default;
  54. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  55. {
  56. if(heroChainPass)
  57. return;
  58. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  59. const PlayerColor fowPlayer = ai->playerID;
  60. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(fowPlayer)->fogOfWarMap;
  61. const int3 sizes = gs->getMapSize();
  62. parallel_for(blocked_range<size_t>(0, sizes.x), [&](const blocked_range<size_t>& r)
  63. {
  64. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  65. const bool useFlying = options.useFlying;
  66. const bool useWaterWalking = options.useWaterWalking;
  67. const PlayerColor player = playerID;
  68. int3 pos;
  69. for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
  70. {
  71. for(pos.y = 0; pos.y < sizes.y; ++pos.y)
  72. {
  73. for(pos.z = 0; pos.z < sizes.z; ++pos.z)
  74. {
  75. const TerrainTile * tile = &gs->map->getTile(pos);
  76. switch(tile->terType)
  77. {
  78. case ETerrainType::ROCK:
  79. break;
  80. case ETerrainType::WATER:
  81. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  82. if(useFlying)
  83. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  84. if(useWaterWalking)
  85. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  86. break;
  87. default:
  88. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  89. if(useFlying)
  90. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. });
  97. }
  98. void AINodeStorage::clear()
  99. {
  100. CCreature::DisableChildLinkage = true;
  101. actors.clear();
  102. CCreature::DisableChildLinkage = false;
  103. heroChainPass = EHeroChainPass::INITIAL;
  104. heroChainTurn = 0;
  105. heroChainMaxTurns = 1;
  106. turnDistanceLimit[HeroRole::MAIN] = 255;
  107. turnDistanceLimit[HeroRole::SCOUT] = 255;
  108. }
  109. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  110. {
  111. return static_cast<const AIPathNode *>(node);
  112. }
  113. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  114. {
  115. auto aiNode = static_cast<AIPathNode *>(node);
  116. updater(aiNode);
  117. }
  118. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  119. const int3 & pos,
  120. const EPathfindingLayer layer,
  121. const ChainActor * actor)
  122. {
  123. int bucketIndex = ((uintptr_t)actor) % BUCKET_COUNT;
  124. int bucketOffset = bucketIndex * BUCKET_SIZE;
  125. auto chains = nodes.get(pos, layer);
  126. if(chains[0].blocked())
  127. {
  128. return boost::none;
  129. }
  130. for(auto i = BUCKET_SIZE - 1; i >= 0; i--)
  131. {
  132. AIPathNode & node = chains[i + bucketOffset];
  133. if(node.actor == actor)
  134. {
  135. return &node;
  136. }
  137. if(!node.actor)
  138. {
  139. node.actor = actor;
  140. return &node;
  141. }
  142. }
  143. return boost::none;
  144. }
  145. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  146. {
  147. if(heroChainPass)
  148. {
  149. calculateTownPortalTeleportations(heroChain);
  150. return heroChain;
  151. }
  152. std::vector<CGPathNode *> initialNodes;
  153. for(auto actorPtr : actors)
  154. {
  155. ChainActor * actor = actorPtr.get();
  156. AIPathNode * initialNode =
  157. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  158. .get();
  159. if(!initialNode)
  160. continue;
  161. initialNode->inPQ = false;
  162. initialNode->pq = nullptr;
  163. initialNode->turns = actor->initialTurn;
  164. initialNode->moveRemains = actor->initialMovement;
  165. initialNode->danger = 0;
  166. initialNode->setCost(actor->initialTurn);
  167. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  168. if(actor->isMovable)
  169. {
  170. initialNodes.push_back(initialNode);
  171. }
  172. else
  173. {
  174. initialNode->locked = true;
  175. }
  176. }
  177. calculateTownPortalTeleportations(initialNodes);
  178. return initialNodes;
  179. }
  180. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  181. {
  182. for(AIPathNode & heroNode : nodes.get(coord, layer))
  183. {
  184. heroNode.actor = nullptr;
  185. heroNode.danger = 0;
  186. heroNode.manaCost = 0;
  187. heroNode.specialAction.reset();
  188. heroNode.armyLoss = 0;
  189. heroNode.chainOther = nullptr;
  190. heroNode.update(coord, layer, accessibility);
  191. }
  192. }
  193. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  194. {
  195. const AIPathNode * srcNode = getAINode(source.node);
  196. updateAINode(destination.node, [&](AIPathNode * dstNode)
  197. {
  198. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  199. if(srcNode->specialAction || srcNode->chainOther)
  200. {
  201. // there is some action on source tile which should be performed before we can bypass it
  202. destination.node->theNodeBefore = source.node;
  203. }
  204. if(dstNode->specialAction && dstNode->actor)
  205. {
  206. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  207. }
  208. });
  209. }
  210. void AINodeStorage::commit(
  211. AIPathNode * destination,
  212. const AIPathNode * source,
  213. CGPathNode::ENodeAction action,
  214. int turn,
  215. int movementLeft,
  216. float cost) const
  217. {
  218. destination->action = action;
  219. destination->setCost(cost);
  220. destination->moveRemains = movementLeft;
  221. destination->turns = turn;
  222. destination->armyLoss = source->armyLoss;
  223. destination->manaCost = source->manaCost;
  224. destination->danger = source->danger;
  225. destination->theNodeBefore = source->theNodeBefore;
  226. destination->chainOther = nullptr;
  227. #if PATHFINDER_TRACE_LEVEL >= 2
  228. logAi->trace(
  229. "Commited %s -> %s, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  230. source->coord.toString(),
  231. destination->coord.toString(),
  232. destination->getCost(),
  233. std::to_string(destination->turns),
  234. destination->moveRemains,
  235. destination->actor->toString(),
  236. destination->actor->chainMask,
  237. destination->actor->armyValue);
  238. #endif
  239. if(destination->turns <= heroChainTurn)
  240. {
  241. commitedTiles.insert(destination->coord);
  242. }
  243. }
  244. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  245. const PathNodeInfo & source,
  246. const PathfinderConfig * pathfinderConfig,
  247. const CPathfinderHelper * pathfinderHelper)
  248. {
  249. std::vector<CGPathNode *> neighbours;
  250. neighbours.reserve(16);
  251. const AIPathNode * srcNode = getAINode(source.node);
  252. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  253. for(auto & neighbour : accessibleNeighbourTiles)
  254. {
  255. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  256. {
  257. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  258. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  259. continue;
  260. neighbours.push_back(nextNode.get());
  261. }
  262. }
  263. return neighbours;
  264. }
  265. EPathfindingLayer phisycalLayers[2] = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
  266. bool AINodeStorage::increaseHeroChainTurnLimit()
  267. {
  268. if(heroChainTurn >= heroChainMaxTurns)
  269. return false;
  270. heroChainTurn++;
  271. commitedTiles.clear();
  272. for(auto layer : phisycalLayers)
  273. {
  274. foreach_tile_pos([&](const int3 & pos)
  275. {
  276. auto chains = nodes.get(pos, layer);
  277. if(!chains[0].blocked())
  278. {
  279. for(AIPathNode & node : chains)
  280. {
  281. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  282. {
  283. commitedTiles.insert(pos);
  284. break;
  285. }
  286. }
  287. }
  288. });
  289. }
  290. return true;
  291. }
  292. bool AINodeStorage::calculateHeroChainFinal()
  293. {
  294. heroChainPass = EHeroChainPass::FINAL;
  295. heroChain.resize(0);
  296. for(auto layer : phisycalLayers)
  297. {
  298. foreach_tile_pos([&](const int3 & pos)
  299. {
  300. auto chains = nodes.get(pos, layer);
  301. if(!chains[0].blocked())
  302. {
  303. for(AIPathNode & node : chains)
  304. {
  305. if(node.turns > heroChainTurn
  306. && !node.locked
  307. && node.action != CGPathNode::ENodeAction::UNKNOWN
  308. && node.actor->actorExchangeCount > 1
  309. && !hasBetterChain(&node, &node, chains))
  310. {
  311. heroChain.push_back(&node);
  312. }
  313. }
  314. }
  315. });
  316. }
  317. return heroChain.size();
  318. }
  319. struct DelayedWork
  320. {
  321. AIPathNode * carrier;
  322. AIPathNode * other;
  323. DelayedWork()
  324. {
  325. }
  326. DelayedWork(AIPathNode * carrier, AIPathNode * other) : carrier(carrier), other(other)
  327. {
  328. }
  329. };
  330. class HeroChainCalculationTask
  331. {
  332. private:
  333. AISharedStorage & nodes;
  334. AINodeStorage & storage;
  335. std::vector<AIPathNode *> existingChains;
  336. std::vector<ExchangeCandidate> newChains;
  337. uint64_t chainMask;
  338. int heroChainTurn;
  339. std::vector<CGPathNode *> heroChain;
  340. const std::vector<int3> & tiles;
  341. public:
  342. HeroChainCalculationTask(
  343. AINodeStorage & storage, AISharedStorage & nodes, const std::vector<int3> & tiles, uint64_t chainMask, int heroChainTurn)
  344. :existingChains(), newChains(), nodes(nodes), storage(storage), chainMask(chainMask), heroChainTurn(heroChainTurn), heroChain(), tiles(tiles)
  345. {
  346. existingChains.reserve(NUM_CHAINS);
  347. newChains.reserve(NUM_CHAINS);
  348. }
  349. void execute(const blocked_range<size_t>& r)
  350. {
  351. for(int i = r.begin(); i != r.end(); i++)
  352. {
  353. auto & pos = tiles[i];
  354. for(auto layer : phisycalLayers)
  355. {
  356. auto chains = nodes.get(pos, layer);
  357. // fast cut inactive nodes
  358. if(chains[0].blocked())
  359. continue;
  360. existingChains.clear();
  361. newChains.clear();
  362. for(AIPathNode & node : chains)
  363. {
  364. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  365. existingChains.push_back(&node);
  366. }
  367. std::random_shuffle(existingChains.begin(), existingChains.end());
  368. for(AIPathNode * node : existingChains)
  369. {
  370. if(node->actor->isMovable)
  371. {
  372. calculateHeroChain(node, existingChains, newChains);
  373. }
  374. }
  375. cleanupInefectiveChains(newChains);
  376. addHeroChain(newChains);
  377. }
  378. }
  379. }
  380. void calculateHeroChain(
  381. AIPathNode * srcNode,
  382. const std::vector<AIPathNode *> & variants,
  383. std::vector<ExchangeCandidate> & result);
  384. void calculateHeroChain(
  385. AIPathNode * carrier,
  386. AIPathNode * other,
  387. std::vector<ExchangeCandidate> & result);
  388. void cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const;
  389. void addHeroChain(const std::vector<ExchangeCandidate> & result);
  390. ExchangeCandidate calculateExchange(
  391. ChainActor * exchangeActor,
  392. AIPathNode * carrierParentNode,
  393. AIPathNode * otherParentNode) const;
  394. void flushResult(std::vector<CGPathNode *> & result)
  395. {
  396. vstd::concatenate(result, heroChain);
  397. }
  398. };
  399. bool AINodeStorage::calculateHeroChain()
  400. {
  401. heroChainPass = EHeroChainPass::CHAIN;
  402. heroChain.clear();
  403. std::vector<int3> data(commitedTiles.begin(), commitedTiles.end());
  404. CCreature::DisableChildLinkage = true;
  405. auto r = blocked_range<size_t>(0, data.size());
  406. HeroChainCalculationTask task(*this, nodes, data, chainMask, heroChainTurn);
  407. task.execute(r);
  408. task.flushResult(heroChain);
  409. CCreature::DisableChildLinkage = false;
  410. commitedTiles.clear();
  411. return !heroChain.empty();
  412. }
  413. bool AINodeStorage::selectFirstActor()
  414. {
  415. if(actors.empty())
  416. return false;
  417. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  418. {
  419. return actor->armyValue;
  420. });
  421. chainMask = strongest->chainMask;
  422. commitedTilesInitial = commitedTiles;
  423. return true;
  424. }
  425. bool AINodeStorage::selectNextActor()
  426. {
  427. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  428. {
  429. return actor->chainMask == chainMask;
  430. });
  431. auto nextActor = actors.end();
  432. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  433. {
  434. if(actor->get()->armyValue > currentActor->get()->armyValue
  435. || actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor)
  436. {
  437. continue;
  438. }
  439. if(nextActor == actors.end()
  440. || actor->get()->armyValue > nextActor->get()->armyValue)
  441. {
  442. nextActor = actor;
  443. }
  444. }
  445. if(nextActor != actors.end())
  446. {
  447. if(nextActor->get()->armyValue < MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR)
  448. return false;
  449. chainMask = nextActor->get()->chainMask;
  450. commitedTiles = commitedTilesInitial;
  451. return true;
  452. }
  453. return false;
  454. }
  455. void HeroChainCalculationTask::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  456. {
  457. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  458. {
  459. auto pos = chainInfo.coord;
  460. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  461. auto isNotEffective = storage.hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  462. || storage.hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  463. #if PATHFINDER_TRACE_LEVEL >= 2
  464. if(isNotEffective)
  465. {
  466. logAi->trace(
  467. "Skip exchange %s[%x] -> %s[%x] at %s is ineficient",
  468. chainInfo.otherParent->actor->toString(),
  469. chainInfo.otherParent->actor->chainMask,
  470. chainInfo.carrierParent->actor->toString(),
  471. chainInfo.carrierParent->actor->chainMask,
  472. chainInfo.carrierParent->coord.toString());
  473. }
  474. #endif
  475. return isNotEffective;
  476. });
  477. }
  478. void HeroChainCalculationTask::calculateHeroChain(
  479. AIPathNode * srcNode,
  480. const std::vector<AIPathNode *> & variants,
  481. std::vector<ExchangeCandidate> & result)
  482. {
  483. for(AIPathNode * node : variants)
  484. {
  485. if(node == srcNode || !node->actor)
  486. continue;
  487. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  488. continue;
  489. if(node->action == CGPathNode::ENodeAction::BATTLE
  490. || node->action == CGPathNode::ENodeAction::TELEPORT_BATTLE
  491. || node->action == CGPathNode::ENodeAction::TELEPORT_NORMAL
  492. || node->action == CGPathNode::ENodeAction::TELEPORT_BLOCKING_VISIT)
  493. {
  494. continue;
  495. }
  496. if(node->turns > heroChainTurn
  497. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  498. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  499. {
  500. #if PATHFINDER_TRACE_LEVEL >= 2
  501. logAi->trace(
  502. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  503. node->actor->toString(),
  504. node->actor->chainMask,
  505. srcNode->actor->toString(),
  506. srcNode->actor->chainMask,
  507. srcNode->coord.toString(),
  508. (node->turns > heroChainTurn
  509. ? "turn limit"
  510. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  511. ? "action unknown"
  512. : "chain mask"));
  513. #endif
  514. continue;
  515. }
  516. #if PATHFINDER_TRACE_LEVEL >= 2
  517. logAi->trace(
  518. "Thy exchange %s[%x] -> %s[%x] at %s",
  519. node->actor->toString(),
  520. node->actor->chainMask,
  521. srcNode->actor->toString(),
  522. srcNode->actor->chainMask,
  523. srcNode->coord.toString());
  524. #endif
  525. calculateHeroChain(srcNode, node, result);
  526. }
  527. }
  528. void HeroChainCalculationTask::calculateHeroChain(
  529. AIPathNode * carrier,
  530. AIPathNode * other,
  531. std::vector<ExchangeCandidate> & result)
  532. {
  533. if(carrier->armyLoss < carrier->actor->armyValue
  534. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  535. && carrier->action != CGPathNode::BLOCKING_VISIT
  536. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue))
  537. {
  538. #if PATHFINDER_TRACE_LEVEL >= 2
  539. logAi->trace(
  540. "Exchange allowed %s[%x] -> %s[%x] at %s",
  541. other->actor->toString(),
  542. other->actor->chainMask,
  543. carrier->actor->toString(),
  544. carrier->actor->chainMask,
  545. carrier->coord.toString());
  546. #endif
  547. if(other->actor->isMovable)
  548. {
  549. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  550. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  551. if(hasLessMp && hasLessExperience)
  552. {
  553. #if PATHFINDER_TRACE_LEVEL >= 2
  554. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  555. #endif
  556. return;
  557. }
  558. }
  559. auto newActor = carrier->actor->tryExchange(other->actor);
  560. if(newActor) result.push_back(calculateExchange(newActor, carrier, other));
  561. }
  562. }
  563. void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate> & result)
  564. {
  565. for(const ExchangeCandidate & chainInfo : result)
  566. {
  567. auto carrier = chainInfo.carrierParent;
  568. auto newActor = chainInfo.actor;
  569. auto other = chainInfo.otherParent;
  570. auto chainNodeOptional = storage.getOrCreateNode(carrier->coord, carrier->layer, newActor);
  571. if(!chainNodeOptional)
  572. {
  573. #if PATHFINDER_TRACE_LEVEL >= 2
  574. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  575. #endif
  576. continue;
  577. }
  578. auto exchangeNode = chainNodeOptional.get();
  579. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  580. {
  581. #if PATHFINDER_TRACE_LEVEL >= 2
  582. logAi->trace(
  583. "Skip exchange %s[%x] -> %s[%x] at %s because node is in use",
  584. other->actor->toString(),
  585. other->actor->chainMask,
  586. carrier->actor->toString(),
  587. carrier->actor->chainMask,
  588. carrier->coord.toString());
  589. #endif
  590. continue;
  591. }
  592. if(exchangeNode->turns != 0xFF && exchangeNode->getCost() < chainInfo.getCost())
  593. {
  594. #if PATHFINDER_TRACE_LEVEL >= 2
  595. logAi->trace(
  596. "Skip exchange %s[%x] -> %s[%x] at %s because not effective enough. %f < %f",
  597. other->actor->toString(),
  598. other->actor->chainMask,
  599. carrier->actor->toString(),
  600. carrier->actor->chainMask,
  601. carrier->coord.toString(),
  602. exchangeNode->getCost(),
  603. chainInfo.getCost());
  604. #endif
  605. continue;
  606. }
  607. storage.commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.getCost());
  608. if(carrier->specialAction || carrier->chainOther)
  609. {
  610. // there is some action on source tile which should be performed before we can bypass it
  611. exchangeNode->theNodeBefore = carrier;
  612. }
  613. if(exchangeNode->actor->actorAction)
  614. {
  615. exchangeNode->theNodeBefore = carrier;
  616. exchangeNode->specialAction = exchangeNode->actor->actorAction;
  617. }
  618. exchangeNode->chainOther = other;
  619. exchangeNode->armyLoss = chainInfo.armyLoss;
  620. #if PATHFINDER_TRACE_LEVEL >= 2
  621. logAi->trace(
  622. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  623. exchangeNode->coord.toString(),
  624. other->actor->toString(),
  625. exchangeNode->actor->toString(),
  626. exchangeNode->actor->chainMask,
  627. exchangeNode->getCost(),
  628. std::to_string(exchangeNode->turns),
  629. exchangeNode->moveRemains,
  630. exchangeNode->actor->armyValue);
  631. #endif
  632. heroChain.push_back(exchangeNode);
  633. }
  634. }
  635. ExchangeCandidate HeroChainCalculationTask::calculateExchange(
  636. ChainActor * exchangeActor,
  637. AIPathNode * carrierParentNode,
  638. AIPathNode * otherParentNode) const
  639. {
  640. ExchangeCandidate candidate;
  641. candidate.layer = carrierParentNode->layer;
  642. candidate.coord = carrierParentNode->coord;
  643. candidate.carrierParent = carrierParentNode;
  644. candidate.otherParent = otherParentNode;
  645. candidate.actor = exchangeActor;
  646. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  647. candidate.turns = carrierParentNode->turns;
  648. candidate.setCost(carrierParentNode->getCost() + otherParentNode->getCost() / 1000.0);
  649. candidate.moveRemains = carrierParentNode->moveRemains;
  650. if(carrierParentNode->turns < otherParentNode->turns)
  651. {
  652. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  653. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  654. + carrierParentNode->moveRemains / (float)moveRemains;
  655. candidate.turns = otherParentNode->turns;
  656. candidate.setCost(candidate.getCost() + waitingCost);
  657. candidate.moveRemains = moveRemains;
  658. }
  659. return candidate;
  660. }
  661. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  662. {
  663. auto aiNode = getAINode(node);
  664. return aiNode->actor->hero;
  665. }
  666. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  667. {
  668. std::set<const CGHeroInstance *> heroes;
  669. for(auto actor : actors)
  670. {
  671. if(actor->hero)
  672. heroes.insert(actor->hero);
  673. }
  674. return heroes;
  675. }
  676. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  677. {
  678. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  679. {
  680. return true;
  681. }
  682. auto aiNode = getAINode(destination.node);
  683. if(heroChainPass != EHeroChainPass::CHAIN
  684. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  685. {
  686. return true;
  687. }
  688. return false;
  689. }
  690. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  691. {
  692. playerID = ai->playerID;
  693. for(auto & hero : heroes)
  694. {
  695. uint64_t mask = FirstActorMask << actors.size();
  696. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
  697. if(actor->hero->tempOwner != ai->playerID)
  698. {
  699. bool onLand = !actor->hero->boat;
  700. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  701. }
  702. playerID = actor->hero->tempOwner;
  703. actors.push_back(actor);
  704. }
  705. }
  706. void AINodeStorage::setTownsAndDwellings(
  707. const std::vector<const CGTownInstance *> & towns,
  708. const std::set<const CGObjectInstance *> & visitableObjs)
  709. {
  710. for(auto town : towns)
  711. {
  712. uint64_t mask = FirstActorMask << actors.size();
  713. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
  714. // check defence imrove
  715. if(!town->garrisonHero)
  716. {
  717. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  718. }
  719. }
  720. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  721. auto waitForGrowth = dayOfWeek > 4;*/
  722. for(auto obj: visitableObjs)
  723. {
  724. if(obj->ID == Obj::HILL_FORT)
  725. {
  726. uint64_t mask = FirstActorMask << actors.size();
  727. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  728. }
  729. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  730. if(dwelling)
  731. {
  732. uint64_t mask = 1 << actors.size();
  733. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  734. if(dwellingActor->creatureSet->getArmyStrength())
  735. {
  736. actors.push_back(dwellingActor);
  737. }
  738. if(waitForGrowth)
  739. {
  740. mask = 1 << actors.size();
  741. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  742. if(dwellingActor->creatureSet->getArmyStrength())
  743. {
  744. actors.push_back(dwellingActor);
  745. }
  746. }
  747. }*/
  748. }
  749. }
  750. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  751. const PathNodeInfo & source,
  752. const PathfinderConfig * pathfinderConfig,
  753. const CPathfinderHelper * pathfinderHelper)
  754. {
  755. std::vector<CGPathNode *> neighbours;
  756. if(source.isNodeObjectVisitable())
  757. {
  758. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  759. auto srcNode = getAINode(source.node);
  760. for(auto & neighbour : accessibleExits)
  761. {
  762. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  763. if(!node)
  764. continue;
  765. neighbours.push_back(node.get());
  766. }
  767. }
  768. return neighbours;
  769. }
  770. struct TowmPortalFinder
  771. {
  772. const std::vector<CGPathNode *> & initialNodes;
  773. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  774. uint64_t movementNeeded;
  775. const ChainActor * actor;
  776. const CGHeroInstance * hero;
  777. std::vector<const CGTownInstance *> targetTowns;
  778. AINodeStorage * nodeStorage;
  779. SpellID spellID;
  780. const CSpell * townPortal;
  781. TowmPortalFinder(
  782. const ChainActor * actor,
  783. const std::vector<CGPathNode *> & initialNodes,
  784. std::vector<const CGTownInstance *> targetTowns,
  785. AINodeStorage * nodeStorage)
  786. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  787. targetTowns(targetTowns), nodeStorage(nodeStorage)
  788. {
  789. spellID = SpellID::TOWN_PORTAL;
  790. townPortal = spellID.toSpell();
  791. // TODO: Copy/Paste from TownPortalMechanics
  792. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  793. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  794. }
  795. bool actorCanCastTownPortal()
  796. {
  797. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  798. }
  799. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  800. {
  801. CGPathNode * bestNode = nullptr;
  802. for(CGPathNode * node : initialNodes)
  803. {
  804. auto aiNode = nodeStorage->getAINode(node);
  805. if(aiNode->actor->baseActor != actor
  806. || node->layer != EPathfindingLayer::LAND
  807. || node->moveRemains < movementNeeded)
  808. {
  809. continue;
  810. }
  811. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  812. {
  813. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  814. {
  815. return node->coord.dist2dSQ(t->visitablePos());
  816. });
  817. if(targetTown != nearestTown)
  818. continue;
  819. }
  820. if(!bestNode || bestNode->getCost() > node->getCost())
  821. bestNode = node;
  822. }
  823. return bestNode;
  824. }
  825. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  826. {
  827. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  828. if(!bestNode)
  829. return boost::none;
  830. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  831. if(!nodeOptional)
  832. return boost::none;
  833. AIPathNode * node = nodeOptional.get();
  834. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  835. movementCost += bestNode->getCost();
  836. if(node->action == CGPathNode::UNKNOWN || node->getCost() > movementCost)
  837. {
  838. nodeStorage->commit(
  839. node,
  840. nodeStorage->getAINode(bestNode),
  841. CGPathNode::TELEPORT_NORMAL,
  842. bestNode->turns,
  843. bestNode->moveRemains - movementNeeded,
  844. movementCost);
  845. node->theNodeBefore = bestNode;
  846. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  847. }
  848. return nodeOptional;
  849. }
  850. };
  851. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  852. {
  853. std::set<const ChainActor *> actorsOfInitial;
  854. for(const CGPathNode * node : initialNodes)
  855. {
  856. auto aiNode = getAINode(node);
  857. actorsOfInitial.insert(aiNode->actor->baseActor);
  858. }
  859. std::map<const CGHeroInstance *, int> maskMap;
  860. for(std::shared_ptr<ChainActor> basicActor : actors)
  861. {
  862. if(basicActor->hero)
  863. maskMap[basicActor->hero] = basicActor->chainMask;
  864. }
  865. for(const ChainActor * actor : actorsOfInitial)
  866. {
  867. if(!actor->hero)
  868. continue;
  869. auto towns = cb->getTownsInfo(false);
  870. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  871. {
  872. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  873. });
  874. if(!towns.size())
  875. {
  876. return; // no towns no need to run loop further
  877. }
  878. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  879. if(townPortalFinder.actorCanCastTownPortal())
  880. {
  881. for(const CGTownInstance * targetTown : towns)
  882. {
  883. // TODO: allow to hide visiting hero in garrison
  884. if(targetTown->visitingHero)
  885. {
  886. auto basicMask = maskMap[targetTown->visitingHero.get()];
  887. bool heroIsInChain = (actor->chainMask & basicMask) != 0;
  888. bool sameActorInTown = actor->chainMask == basicMask;
  889. if(sameActorInTown || !heroIsInChain)
  890. continue;
  891. }
  892. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  893. if(nodeOptional)
  894. {
  895. #if PATHFINDER_TRACE_LEVEL >= 1
  896. logAi->trace("Adding town portal node at %s", targetTown->name);
  897. #endif
  898. initialNodes.push_back(nodeOptional.get());
  899. }
  900. }
  901. }
  902. }
  903. }
  904. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  905. {
  906. auto pos = destination.coord;
  907. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  908. return hasBetterChain(source.node, getAINode(destination.node), chains);
  909. }
  910. template<class NodeRange>
  911. bool AINodeStorage::hasBetterChain(
  912. const CGPathNode * source,
  913. const AIPathNode * candidateNode,
  914. const NodeRange & chains) const
  915. {
  916. auto candidateActor = candidateNode->actor;
  917. for(const AIPathNode & node : chains)
  918. {
  919. auto sameNode = node.actor == candidateNode->actor;
  920. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  921. {
  922. continue;
  923. }
  924. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  925. {
  926. if(node.getCost() < candidateNode->getCost())
  927. {
  928. #if PATHFINDER_TRACE_LEVEL >= 2
  929. logAi->trace(
  930. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  931. source->coord.toString(),
  932. candidateNode->coord.toString(),
  933. candidateNode->actor->hero->name,
  934. candidateNode->actor->chainMask,
  935. candidateNode->actor->armyValue,
  936. node.moveRemains - candidateNode->moveRemains);
  937. #endif
  938. return true;
  939. }
  940. }
  941. if(candidateActor->chainMask != node.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  942. continue;
  943. auto nodeActor = node.actor;
  944. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  945. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  946. if(nodeArmyValue > candidateArmyValue
  947. && node.getCost() <= candidateNode->getCost())
  948. {
  949. #if PATHFINDER_TRACE_LEVEL >= 2
  950. logAi->trace(
  951. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  952. source->coord.toString(),
  953. candidateNode->coord.toString(),
  954. candidateNode->actor->hero->name,
  955. candidateNode->actor->chainMask,
  956. candidateNode->actor->armyValue,
  957. node.moveRemains - candidateNode->moveRemains);
  958. #endif
  959. return true;
  960. }
  961. if(heroChainPass == EHeroChainPass::FINAL)
  962. {
  963. if(nodeArmyValue == candidateArmyValue
  964. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  965. && node.getCost() <= candidateNode->getCost())
  966. {
  967. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  968. && node.getCost() == candidateNode->getCost()
  969. && &node < candidateNode)
  970. {
  971. continue;
  972. }
  973. #if AI_TRACE_LEVEL >= 2
  974. logAi->trace(
  975. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  976. source->coord.toString(),
  977. candidateNode->coord.toString(),
  978. candidateNode->actor->hero->name,
  979. candidateNode->actor->chainMask,
  980. candidateNode->actor->armyValue,
  981. node.moveRemains - candidateNode->moveRemains);
  982. #endif
  983. return true;
  984. }
  985. }
  986. }
  987. return false;
  988. }
  989. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  990. {
  991. auto chains = nodes.get(pos, layer);
  992. for(const AIPathNode & node : chains)
  993. {
  994. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  995. && node.actor && node.actor->hero == hero.h)
  996. {
  997. return true;
  998. }
  999. }
  1000. return false;
  1001. }
  1002. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  1003. {
  1004. std::vector<AIPath> paths;
  1005. paths.reserve(NUM_CHAINS / 4);
  1006. auto chains = nodes.get(pos, isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  1007. for(const AIPathNode & node : chains)
  1008. {
  1009. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  1010. {
  1011. continue;
  1012. }
  1013. AIPath path;
  1014. path.targetHero = node.actor->hero;
  1015. path.heroArmy = node.actor->creatureSet;
  1016. path.armyLoss = node.armyLoss;
  1017. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, false);
  1018. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  1019. path.chainMask = node.actor->chainMask;
  1020. path.exchangeCount = node.actor->actorExchangeCount;
  1021. fillChainInfo(&node, path, -1);
  1022. paths.push_back(path);
  1023. }
  1024. return paths;
  1025. }
  1026. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  1027. {
  1028. while(node != nullptr)
  1029. {
  1030. if(!node->actor->hero)
  1031. return;
  1032. if(node->chainOther)
  1033. fillChainInfo(node->chainOther, path, parentIndex);
  1034. //if(node->actor->hero->visitablePos() != node->coord)
  1035. {
  1036. AIPathNodeInfo pathNode;
  1037. pathNode.cost = node->getCost();
  1038. pathNode.targetHero = node->actor->hero;
  1039. pathNode.chainMask = node->actor->chainMask;
  1040. pathNode.specialAction = node->specialAction;
  1041. pathNode.turns = node->turns;
  1042. pathNode.danger = node->danger;
  1043. pathNode.coord = node->coord;
  1044. pathNode.parentIndex = parentIndex;
  1045. pathNode.actionIsBlocked = false;
  1046. if(pathNode.specialAction)
  1047. {
  1048. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  1049. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(targetNode);
  1050. }
  1051. parentIndex = path.nodes.size();
  1052. path.nodes.push_back(pathNode);
  1053. }
  1054. node = getAINode(node->theNodeBefore);
  1055. }
  1056. }
  1057. AIPath::AIPath()
  1058. : nodes({})
  1059. {
  1060. }
  1061. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  1062. {
  1063. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  1064. {
  1065. if(node->specialAction && node->actionIsBlocked)
  1066. return node->specialAction;
  1067. }
  1068. return std::shared_ptr<const SpecialAction>();
  1069. }
  1070. int3 AIPath::firstTileToGet() const
  1071. {
  1072. if(nodes.size())
  1073. {
  1074. return nodes.back().coord;
  1075. }
  1076. return int3(-1, -1, -1);
  1077. }
  1078. int3 AIPath::targetTile() const
  1079. {
  1080. if(nodes.size())
  1081. {
  1082. return targetNode().coord;
  1083. }
  1084. return int3(-1, -1, -1);
  1085. }
  1086. const AIPathNodeInfo & AIPath::firstNode() const
  1087. {
  1088. return nodes.back();
  1089. }
  1090. const AIPathNodeInfo & AIPath::targetNode() const
  1091. {
  1092. auto & node = nodes.front();
  1093. return targetHero == node.targetHero ? node : nodes.at(1);
  1094. }
  1095. uint64_t AIPath::getPathDanger() const
  1096. {
  1097. if(nodes.empty())
  1098. return 0;
  1099. return targetNode().danger;
  1100. }
  1101. float AIPath::movementCost() const
  1102. {
  1103. if(nodes.empty())
  1104. return 0.0f;
  1105. return targetNode().cost;
  1106. }
  1107. uint8_t AIPath::turn() const
  1108. {
  1109. if(nodes.empty())
  1110. return 0;
  1111. return targetNode().turns;
  1112. }
  1113. uint64_t AIPath::getHeroStrength() const
  1114. {
  1115. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  1116. }
  1117. uint64_t AIPath::getTotalDanger() const
  1118. {
  1119. uint64_t pathDanger = getPathDanger();
  1120. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1121. return danger;
  1122. }
  1123. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1124. {
  1125. if(targetHero == hero)
  1126. return true;
  1127. for(auto node : nodes)
  1128. {
  1129. if(node.targetHero == hero)
  1130. return true;
  1131. }
  1132. return false;
  1133. }
  1134. uint64_t AIPath::getTotalArmyLoss() const
  1135. {
  1136. return armyLoss + targetObjectArmyLoss;
  1137. }
  1138. std::string AIPath::toString() const
  1139. {
  1140. std::stringstream str;
  1141. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1142. for(auto node : nodes)
  1143. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1144. return str.str();
  1145. }