AINodeStorage.cpp 37 KB

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