AINodeStorage.cpp 36 KB

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