2
0

AINodeStorage.cpp 44 KB

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