AINodeStorage.cpp 39 KB

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