AINodeStorage.cpp 38 KB

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