2
0

AINodeStorage.cpp 42 KB

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