AINodeStorage.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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 "../Engine/Nullkiller.h"
  15. #include "../../../lib/callback/IGameInfoCallback.h"
  16. #include "../../../lib/mapping/CMap.h"
  17. #include "../../../lib/pathfinder/CPathfinder.h"
  18. #include "../../../lib/pathfinder/PathfinderUtil.h"
  19. #include "../../../lib/pathfinder/PathfinderOptions.h"
  20. #include "../../../lib/IGameSettings.h"
  21. #include "../../../lib/CPlayerState.h"
  22. namespace NKAI
  23. {
  24. std::shared_ptr<boost::multi_array<AIPathNode, 4>> AISharedStorage::shared;
  25. uint32_t AISharedStorage::version = 0;
  26. std::mutex AISharedStorage::locker;
  27. std::set<int3> committedTiles;
  28. std::set<int3> committedTilesInitial;
  29. const uint64_t FirstActorMask = 1;
  30. const uint64_t MIN_ARMY_STRENGTH_FOR_CHAIN = 5000;
  31. const uint64_t MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR = 1000;
  32. const uint64_t CHAIN_MAX_DEPTH = 4;
  33. const bool DO_NOT_SAVE_TO_COMMITTED_TILES = false;
  34. AISharedStorage::AISharedStorage(int3 sizes, int numChains)
  35. {
  36. if(!shared){
  37. shared.reset(new boost::multi_array<AIPathNode, 4>(
  38. boost::extents[sizes.z][sizes.x][sizes.y][numChains]));
  39. nodes = shared;
  40. foreach_tile_pos([&](const int3 & pos)
  41. {
  42. for(auto i = 0; i < numChains; i++)
  43. {
  44. auto & node = get(pos)[i];
  45. node.version = -1;
  46. node.coord = pos;
  47. }
  48. });
  49. }
  50. else
  51. nodes = shared;
  52. }
  53. AISharedStorage::~AISharedStorage()
  54. {
  55. nodes.reset();
  56. if(shared && shared.use_count() == 1)
  57. {
  58. shared.reset();
  59. }
  60. }
  61. void AIPathNode::addSpecialAction(std::shared_ptr<const SpecialAction> action)
  62. {
  63. if(!specialAction)
  64. {
  65. specialAction = action;
  66. }
  67. else
  68. {
  69. auto parts = specialAction->getParts();
  70. if(parts.empty())
  71. {
  72. parts.push_back(specialAction);
  73. }
  74. parts.push_back(action);
  75. specialAction = std::make_shared<CompositeAction>(parts);
  76. }
  77. }
  78. int AINodeStorage::getBucketCount() const
  79. {
  80. return ai->settings->getPathfinderBucketsCount();
  81. }
  82. int AINodeStorage::getBucketSize() const
  83. {
  84. return ai->settings->getPathfinderBucketSize();
  85. }
  86. AINodeStorage::AINodeStorage(const Nullkiller * ai, const int3 & Sizes)
  87. : sizes(Sizes), ai(ai), cb(ai->cb.get()), nodes(Sizes, ai->settings->getPathfinderBucketSize() * ai->settings->getPathfinderBucketsCount())
  88. {
  89. accessibility = std::make_unique<boost::multi_array<EPathAccessibility, 4>>(
  90. boost::extents[sizes.z][sizes.x][sizes.y][EPathfindingLayer::NUM_LAYERS]);
  91. }
  92. AINodeStorage::~AINodeStorage() = default;
  93. void AINodeStorage::initialize(const PathfinderOptions & options, const IGameInfoCallback & gameInfo)
  94. {
  95. if(heroChainPass != EHeroChainPass::INITIAL)
  96. return;
  97. AISharedStorage::version++;
  98. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  99. const PlayerColor fowPlayer = ai->playerID;
  100. const auto & fow = gameInfo.getPlayerTeam(fowPlayer)->fogOfWarMap;
  101. const int3 sizes = gameInfo.getMapSize();
  102. //Each thread gets different x, but an array of y located next to each other in memory
  103. tbb::parallel_for(tbb::blocked_range<size_t>(0, sizes.x), [&](const tbb::blocked_range<size_t>& r)
  104. {
  105. int3 pos;
  106. for(pos.z = 0; pos.z < sizes.z; ++pos.z)
  107. {
  108. const bool useFlying = options.useFlying;
  109. const bool useWaterWalking = options.useWaterWalking;
  110. const PlayerColor player = playerID;
  111. for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
  112. {
  113. for(pos.y = 0; pos.y < sizes.y; ++pos.y)
  114. {
  115. const TerrainTile * tile = gameInfo.getTile(pos);
  116. if (!tile->getTerrain()->isPassable())
  117. continue;
  118. if (tile->isWater())
  119. {
  120. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, *tile, fow, player, gameInfo));
  121. if (useFlying)
  122. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, *tile, fow, player, gameInfo));
  123. if (useWaterWalking)
  124. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, *tile, fow, player, gameInfo));
  125. }
  126. else
  127. {
  128. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, *tile, fow, player, gameInfo));
  129. if (useFlying)
  130. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, *tile, fow, player, gameInfo));
  131. }
  132. }
  133. }
  134. }
  135. });
  136. }
  137. void AINodeStorage::clear()
  138. {
  139. actors.clear();
  140. committedTiles.clear();
  141. heroChainPass = EHeroChainPass::INITIAL;
  142. heroChainTurn = 0;
  143. heroChainMaxTurns = 1;
  144. turnDistanceLimit[HeroRole::MAIN] = 255;
  145. turnDistanceLimit[HeroRole::SCOUT] = 255;
  146. }
  147. std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  148. const int3 & pos,
  149. const EPathfindingLayer layer,
  150. const ChainActor * actor)
  151. {
  152. int bucketIndex = ((uintptr_t)actor + layer.getNum()) % ai->settings->getPathfinderBucketsCount();
  153. int bucketOffset = bucketIndex * ai->settings->getPathfinderBucketSize();
  154. auto chains = nodes.get(pos);
  155. if(blocked(pos, layer))
  156. {
  157. return std::nullopt;
  158. }
  159. for(auto i = ai->settings->getPathfinderBucketSize() - 1; i >= 0; i--)
  160. {
  161. AIPathNode & node = chains[i + bucketOffset];
  162. if(node.version != AISharedStorage::version)
  163. {
  164. node.reset(layer, getAccessibility(pos, layer));
  165. node.version = AISharedStorage::version;
  166. node.actor = actor;
  167. return &node;
  168. }
  169. if(node.actor == actor && node.layer == layer)
  170. {
  171. return &node;
  172. }
  173. }
  174. return std::nullopt;
  175. }
  176. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  177. {
  178. if(heroChainPass)
  179. {
  180. if(heroChainTurn == 0)
  181. calculateTownPortalTeleportations(heroChain);
  182. return heroChain;
  183. }
  184. std::vector<CGPathNode *> initialNodes;
  185. for(auto actorPtr : actors)
  186. {
  187. ChainActor * actor = actorPtr.get();
  188. auto allocated = getOrCreateNode(actor->initialPosition, actor->layer, actor);
  189. if(!allocated)
  190. continue;
  191. AIPathNode * initialNode = allocated.value();
  192. initialNode->pq = nullptr;
  193. initialNode->turns = actor->initialTurn;
  194. initialNode->moveRemains = actor->initialMovement;
  195. initialNode->danger = 0;
  196. initialNode->setCost(actor->initialTurn);
  197. initialNode->action = EPathNodeAction::NORMAL;
  198. if(actor->isMovable)
  199. {
  200. initialNodes.push_back(initialNode);
  201. }
  202. else
  203. {
  204. initialNode->locked = true;
  205. }
  206. }
  207. if(heroChainTurn == 0)
  208. calculateTownPortalTeleportations(initialNodes);
  209. return initialNodes;
  210. }
  211. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  212. {
  213. const AIPathNode * srcNode = getAINode(source.node);
  214. updateAINode(destination.node, [&](AIPathNode * dstNode)
  215. {
  216. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  217. // regular pathfinder can not go directly through whirlpool
  218. bool isWhirlpoolTeleport = destination.nodeObject
  219. && destination.nodeObject->ID == Obj::WHIRLPOOL;
  220. if(srcNode->specialAction
  221. || srcNode->chainOther
  222. || isWhirlpoolTeleport)
  223. {
  224. // there is some action on source tile which should be performed before we can bypass it
  225. dstNode->theNodeBefore = source.node;
  226. if(isWhirlpoolTeleport)
  227. {
  228. if(dstNode->actor->creatureSet->Slots().size() == 1
  229. && dstNode->actor->creatureSet->Slots().begin()->second->getCount() == 1)
  230. {
  231. return;
  232. }
  233. const auto & weakest = vstd::minElementByFun(dstNode->actor->creatureSet->Slots(), [](const auto & pair) -> int
  234. {
  235. return pair.second->getCount() * pair.second->getCreatureID().toCreature()->getAIValue();
  236. });
  237. if(weakest == dstNode->actor->creatureSet->Slots().end())
  238. {
  239. logAi->debug("Empty army entering whirlpool detected at tile %s", dstNode->coord.toString());
  240. destination.blocked = true;
  241. return;
  242. }
  243. if(dstNode->actor->creatureSet->getFreeSlots().size())
  244. dstNode->armyLoss += weakest->second->getCreatureID().toCreature()->getAIValue();
  245. else
  246. dstNode->armyLoss += (weakest->second->getCount() + 1) / 2 * weakest->second->getCreatureID().toCreature()->getAIValue();
  247. dstNode->specialAction = AIPathfinding::WhirlpoolAction::instance;
  248. }
  249. }
  250. if(dstNode->specialAction && dstNode->actor)
  251. {
  252. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  253. }
  254. });
  255. }
  256. void AINodeStorage::commit(
  257. AIPathNode * destination,
  258. const AIPathNode * source,
  259. EPathNodeAction action,
  260. int turn,
  261. int movementLeft,
  262. float cost,
  263. bool saveToCommitted) const
  264. {
  265. destination->action = action;
  266. destination->setCost(cost);
  267. destination->moveRemains = movementLeft;
  268. destination->turns = turn;
  269. destination->armyLoss = source->armyLoss;
  270. destination->manaCost = source->manaCost;
  271. destination->danger = source->danger;
  272. destination->theNodeBefore = source->theNodeBefore;
  273. destination->chainOther = nullptr;
  274. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  275. logAi->trace(
  276. "Committed %s -> %s, layer: %d, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  277. source->coord.toString(),
  278. destination->coord.toString(),
  279. destination->layer,
  280. destination->getCost(),
  281. std::to_string(destination->turns),
  282. destination->moveRemains,
  283. destination->actor->toString(),
  284. destination->actor->chainMask,
  285. destination->actor->armyValue);
  286. #endif
  287. if(saveToCommitted && destination->turns <= heroChainTurn)
  288. {
  289. committedTiles.insert(destination->coord);
  290. }
  291. if(destination->turns == source->turns)
  292. {
  293. destination->dayFlags = source->dayFlags;
  294. }
  295. }
  296. void AINodeStorage::calculateNeighbours(
  297. std::vector<CGPathNode *> & result,
  298. const PathNodeInfo & source,
  299. EPathfindingLayer layer,
  300. const PathfinderConfig * pathfinderConfig,
  301. const CPathfinderHelper * pathfinderHelper)
  302. {
  303. NeighbourTilesVector accessibleNeighbourTiles;
  304. result.clear();
  305. pathfinderHelper->calculateNeighbourTiles(accessibleNeighbourTiles, source);
  306. const AIPathNode * srcNode = getAINode(source.node);
  307. for(auto & neighbour : accessibleNeighbourTiles)
  308. {
  309. if(getAccessibility(neighbour, layer) == EPathAccessibility::NOT_SET)
  310. {
  311. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  312. logAi->trace(
  313. "Node %s rejected for %s, layer %d because of inaccessibility",
  314. neighbour.toString(),
  315. source.coord.toString(),
  316. static_cast<int32_t>(layer));
  317. #endif
  318. continue;
  319. }
  320. auto nextNode = getOrCreateNode(neighbour, layer, srcNode->actor);
  321. if(!nextNode)
  322. {
  323. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  324. logAi->trace(
  325. "Failed to allocate node at %s[%d]",
  326. neighbour.toString(),
  327. static_cast<int32_t>(layer));
  328. #endif
  329. continue;
  330. }
  331. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  332. logAi->trace(
  333. "Node %s added to neighbors of %s, layer %d",
  334. neighbour.toString(),
  335. source.coord.toString(),
  336. static_cast<int32_t>(layer));
  337. #endif
  338. result.push_back(nextNode.value());
  339. }
  340. }
  341. constexpr std::array phisycalLayers = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
  342. bool AINodeStorage::increaseHeroChainTurnLimit()
  343. {
  344. if(heroChainTurn >= heroChainMaxTurns)
  345. return false;
  346. heroChainTurn++;
  347. committedTiles.clear();
  348. for(auto layer : phisycalLayers)
  349. {
  350. foreach_tile_pos([&](const int3 & pos)
  351. {
  352. iterateValidNodesUntil(pos, layer, [&](AIPathNode & node)
  353. {
  354. if(node.turns <= heroChainTurn && node.action != EPathNodeAction::UNKNOWN)
  355. {
  356. committedTiles.insert(pos);
  357. return true;
  358. }
  359. return false;
  360. });
  361. });
  362. }
  363. return true;
  364. }
  365. bool AINodeStorage::calculateHeroChainFinal()
  366. {
  367. heroChainPass = EHeroChainPass::FINAL;
  368. heroChain.resize(0);
  369. for(auto layer : phisycalLayers)
  370. {
  371. foreach_tile_pos([&](const int3 & pos)
  372. {
  373. iterateValidNodes(pos, layer, [&](AIPathNode & node)
  374. {
  375. if(node.turns > heroChainTurn
  376. && !node.locked
  377. && node.action != EPathNodeAction::UNKNOWN
  378. && node.actor->actorExchangeCount > 1
  379. && !hasBetterChain(&node, node))
  380. {
  381. heroChain.push_back(&node);
  382. }
  383. });
  384. });
  385. }
  386. return heroChain.size();
  387. }
  388. struct DelayedWork
  389. {
  390. AIPathNode * carrier;
  391. AIPathNode * other;
  392. DelayedWork()
  393. {
  394. }
  395. DelayedWork(AIPathNode * carrier, AIPathNode * other) : carrier(carrier), other(other)
  396. {
  397. }
  398. };
  399. class HeroChainCalculationTask
  400. {
  401. private:
  402. AINodeStorage & storage;
  403. std::vector<AIPathNode *> existingChains;
  404. std::vector<ExchangeCandidate> newChains;
  405. uint64_t chainMask;
  406. int heroChainTurn;
  407. std::vector<CGPathNode *> heroChain;
  408. const std::vector<int3> & tiles;
  409. std::vector<DelayedWork> delayedWork;
  410. public:
  411. HeroChainCalculationTask(
  412. AINodeStorage & storage, const std::vector<int3> & tiles, uint64_t chainMask, int heroChainTurn)
  413. :existingChains(), newChains(), delayedWork(), storage(storage), chainMask(chainMask), heroChainTurn(heroChainTurn), heroChain(), 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::random_device randomDevice;
  421. std::mt19937 randomEngine(randomDevice());
  422. for(int i = r.begin(); i != r.end(); i++)
  423. {
  424. auto & pos = tiles[i];
  425. for(auto layer : phisycalLayers)
  426. {
  427. existingChains.clear();
  428. storage.iterateValidNodes(pos, layer, [this](AIPathNode & node)
  429. {
  430. if(node.turns <= heroChainTurn && node.action != EPathNodeAction::UNKNOWN)
  431. existingChains.push_back(&node);
  432. });
  433. if(existingChains.empty())
  434. continue;
  435. newChains.clear();
  436. std::shuffle(existingChains.begin(), existingChains.end(), randomEngine);
  437. for(AIPathNode * node : existingChains)
  438. {
  439. if(node->actor->isMovable)
  440. {
  441. calculateHeroChain(node, existingChains, newChains);
  442. }
  443. }
  444. for(auto delayed = delayedWork.begin(); delayed != delayedWork.end();)
  445. {
  446. auto newActor = delayed->carrier->actor->tryExchangeNoLock(delayed->other->actor);
  447. if(!newActor.lockAcquired) continue;
  448. if(newActor.actor)
  449. {
  450. newChains.push_back(calculateExchange(newActor.actor, delayed->carrier, delayed->other));
  451. }
  452. delayed++;
  453. }
  454. delayedWork.clear();
  455. cleanupInefectiveChains(newChains);
  456. addHeroChain(newChains);
  457. }
  458. }
  459. }
  460. void calculateHeroChain(
  461. AIPathNode * srcNode,
  462. const std::vector<AIPathNode *> & variants,
  463. std::vector<ExchangeCandidate> & result);
  464. void calculateHeroChain(
  465. AIPathNode * carrier,
  466. AIPathNode * other,
  467. std::vector<ExchangeCandidate> & result);
  468. void cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const;
  469. void addHeroChain(const std::vector<ExchangeCandidate> & result);
  470. ExchangeCandidate calculateExchange(
  471. ChainActor * exchangeActor,
  472. AIPathNode * carrierParentNode,
  473. AIPathNode * otherParentNode) const;
  474. void flushResult(std::vector<CGPathNode *> & result)
  475. {
  476. vstd::concatenate(result, heroChain);
  477. }
  478. };
  479. bool AINodeStorage::calculateHeroChain()
  480. {
  481. heroChainPass = EHeroChainPass::CHAIN;
  482. heroChain.clear();
  483. std::vector<int3> data(committedTiles.begin(), committedTiles.end());
  484. int maxConcurrency = tbb::this_task_arena::max_concurrency();
  485. std::vector<std::vector<CGPathNode *>> results(maxConcurrency);
  486. logAi->trace("Caculating hero chain for %d items", data.size());
  487. tbb::parallel_for(tbb::blocked_range<size_t>(0, data.size()), [&](const tbb::blocked_range<size_t>& r)
  488. {
  489. HeroChainCalculationTask task(*this, data, chainMask, heroChainTurn);
  490. int ourThread = tbb::this_task_arena::current_thread_index();
  491. task.execute(r);
  492. task.flushResult(results.at(ourThread));
  493. });
  494. // FIXME: potentially non-deterministic behavior due to parallel_for
  495. for (const auto & result : results)
  496. vstd::concatenate(heroChain, result);
  497. committedTiles.clear();
  498. return !heroChain.empty();
  499. }
  500. bool AINodeStorage::selectFirstActor()
  501. {
  502. if(actors.empty())
  503. return false;
  504. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  505. {
  506. return actor->armyValue;
  507. });
  508. chainMask = strongest->chainMask;
  509. committedTilesInitial = committedTiles;
  510. return true;
  511. }
  512. bool AINodeStorage::selectNextActor()
  513. {
  514. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  515. {
  516. return actor->chainMask == chainMask;
  517. });
  518. auto nextActor = actors.end();
  519. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  520. {
  521. if(actor->get()->armyValue > currentActor->get()->armyValue
  522. || (actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor))
  523. {
  524. continue;
  525. }
  526. if(nextActor == actors.end()
  527. || actor->get()->armyValue > nextActor->get()->armyValue)
  528. {
  529. nextActor = actor;
  530. }
  531. }
  532. if(nextActor != actors.end())
  533. {
  534. if(nextActor->get()->armyValue < MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR)
  535. return false;
  536. chainMask = nextActor->get()->chainMask;
  537. committedTiles = committedTilesInitial;
  538. return true;
  539. }
  540. return false;
  541. }
  542. uint64_t AINodeStorage::evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const
  543. {
  544. float fightingStrength = ai->heroManager->getFightingStrengthCached(hero);
  545. double ratio = (double)danger / (armyValue * fightingStrength);
  546. return (uint64_t)(armyValue * ratio * ratio);
  547. }
  548. void HeroChainCalculationTask::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  549. {
  550. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  551. {
  552. auto isNotEffective = storage.hasBetterChain(chainInfo.carrierParent, chainInfo)
  553. || storage.hasBetterChain(chainInfo.carrierParent, chainInfo, result);
  554. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  555. if(isNotEffective)
  556. {
  557. logAi->trace(
  558. "Skip exchange %s[%x] -> %s[%x] at %s is inefficient",
  559. chainInfo.otherParent->actor->toString(),
  560. chainInfo.otherParent->actor->chainMask,
  561. chainInfo.carrierParent->actor->toString(),
  562. chainInfo.carrierParent->actor->chainMask,
  563. chainInfo.carrierParent->coord.toString());
  564. }
  565. #endif
  566. return isNotEffective;
  567. });
  568. }
  569. void HeroChainCalculationTask::calculateHeroChain(
  570. AIPathNode * srcNode,
  571. const std::vector<AIPathNode *> & variants,
  572. std::vector<ExchangeCandidate> & result)
  573. {
  574. for(AIPathNode * node : variants)
  575. {
  576. if(node == srcNode || !node->actor || node->version != AISharedStorage::version)
  577. continue;
  578. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  579. continue;
  580. if(node->actor->actorExchangeCount + srcNode->actor->actorExchangeCount > CHAIN_MAX_DEPTH)
  581. continue;
  582. if(node->action == EPathNodeAction::BATTLE
  583. || node->action == EPathNodeAction::TELEPORT_BATTLE
  584. || node->action == EPathNodeAction::TELEPORT_NORMAL
  585. || node->action == EPathNodeAction::DISEMBARK
  586. || node->action == EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  587. {
  588. continue;
  589. }
  590. if(node->turns > heroChainTurn
  591. || (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
  592. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  593. {
  594. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  595. logAi->trace(
  596. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  597. node->actor->toString(),
  598. node->actor->chainMask,
  599. srcNode->actor->toString(),
  600. srcNode->actor->chainMask,
  601. srcNode->coord.toString(),
  602. (node->turns > heroChainTurn
  603. ? "turn limit"
  604. : (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
  605. ? "action unknown"
  606. : "chain mask"));
  607. #endif
  608. continue;
  609. }
  610. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  611. logAi->trace(
  612. "Thy exchange %s[%x] -> %s[%x] at %s",
  613. node->actor->toString(),
  614. node->actor->chainMask,
  615. srcNode->actor->toString(),
  616. srcNode->actor->chainMask,
  617. srcNode->coord.toString());
  618. #endif
  619. calculateHeroChain(srcNode, node, result);
  620. }
  621. }
  622. void HeroChainCalculationTask::calculateHeroChain(
  623. AIPathNode * carrier,
  624. AIPathNode * other,
  625. std::vector<ExchangeCandidate> & result)
  626. {
  627. if(carrier->armyLoss < carrier->actor->armyValue
  628. && (carrier->action != EPathNodeAction::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  629. && carrier->action != EPathNodeAction::BLOCKING_VISIT
  630. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue))
  631. {
  632. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  633. logAi->trace(
  634. "Exchange allowed %s[%x] -> %s[%x] at %s",
  635. other->actor->toString(),
  636. other->actor->chainMask,
  637. carrier->actor->toString(),
  638. carrier->actor->chainMask,
  639. carrier->coord.toString());
  640. #endif
  641. if(other->actor->isMovable)
  642. {
  643. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  644. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  645. if(hasLessMp && hasLessExperience)
  646. {
  647. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  648. logAi->trace("Exchange at %s is inefficient. Blocked.", carrier->coord.toString());
  649. #endif
  650. return;
  651. }
  652. }
  653. auto newActor = carrier->actor->tryExchangeNoLock(other->actor);
  654. if(!newActor.lockAcquired) delayedWork.push_back(DelayedWork(carrier, other));
  655. if(newActor.actor) result.push_back(calculateExchange(newActor.actor, carrier, other));
  656. }
  657. }
  658. void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate> & result)
  659. {
  660. for(const ExchangeCandidate & chainInfo : result)
  661. {
  662. auto carrier = chainInfo.carrierParent;
  663. auto newActor = chainInfo.actor;
  664. auto other = chainInfo.otherParent;
  665. auto chainNodeOptional = storage.getOrCreateNode(carrier->coord, carrier->layer, newActor);
  666. if(!chainNodeOptional)
  667. {
  668. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  669. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  670. #endif
  671. continue;
  672. }
  673. auto exchangeNode = chainNodeOptional.value();
  674. if(exchangeNode->action != EPathNodeAction::UNKNOWN)
  675. {
  676. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  677. logAi->trace(
  678. "Skip exchange %s[%x] -> %s[%x] at %s because node is in use",
  679. other->actor->toString(),
  680. other->actor->chainMask,
  681. carrier->actor->toString(),
  682. carrier->actor->chainMask,
  683. carrier->coord.toString());
  684. #endif
  685. continue;
  686. }
  687. if(exchangeNode->turns != 0xFF && exchangeNode->getCost() < chainInfo.getCost())
  688. {
  689. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  690. logAi->trace(
  691. "Skip exchange %s[%x] -> %s[%x] at %s because not effective enough. %f < %f",
  692. other->actor->toString(),
  693. other->actor->chainMask,
  694. carrier->actor->toString(),
  695. carrier->actor->chainMask,
  696. carrier->coord.toString(),
  697. exchangeNode->getCost(),
  698. chainInfo.getCost());
  699. #endif
  700. continue;
  701. }
  702. storage.commit(
  703. exchangeNode,
  704. carrier,
  705. carrier->action,
  706. chainInfo.turns,
  707. chainInfo.moveRemains,
  708. chainInfo.getCost(),
  709. DO_NOT_SAVE_TO_COMMITTED_TILES);
  710. if(carrier->specialAction || carrier->chainOther)
  711. {
  712. // there is some action on source tile which should be performed before we can bypass it
  713. exchangeNode->theNodeBefore = carrier;
  714. }
  715. if(exchangeNode->actor->actorAction)
  716. {
  717. exchangeNode->theNodeBefore = carrier;
  718. exchangeNode->addSpecialAction(exchangeNode->actor->actorAction);
  719. }
  720. exchangeNode->chainOther = other;
  721. exchangeNode->armyLoss = chainInfo.armyLoss;
  722. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  723. logAi->trace(
  724. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  725. exchangeNode->coord.toString(),
  726. other->actor->toString(),
  727. exchangeNode->actor->toString(),
  728. exchangeNode->actor->chainMask,
  729. exchangeNode->getCost(),
  730. std::to_string(exchangeNode->turns),
  731. exchangeNode->moveRemains,
  732. exchangeNode->actor->armyValue);
  733. #endif
  734. heroChain.push_back(exchangeNode);
  735. }
  736. }
  737. ExchangeCandidate HeroChainCalculationTask::calculateExchange(
  738. ChainActor * exchangeActor,
  739. AIPathNode * carrierParentNode,
  740. AIPathNode * otherParentNode) const
  741. {
  742. ExchangeCandidate candidate;
  743. candidate.layer = carrierParentNode->layer;
  744. candidate.coord = carrierParentNode->coord;
  745. candidate.carrierParent = carrierParentNode;
  746. candidate.otherParent = otherParentNode;
  747. candidate.actor = exchangeActor;
  748. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  749. candidate.turns = carrierParentNode->turns;
  750. candidate.setCost(carrierParentNode->getCost() + otherParentNode->getCost() / 1000.0);
  751. candidate.moveRemains = carrierParentNode->moveRemains;
  752. candidate.danger = carrierParentNode->danger;
  753. candidate.version = carrierParentNode->version;
  754. if(carrierParentNode->turns < otherParentNode->turns)
  755. {
  756. int moveRemains = exchangeActor->maxMovePoints(carrierParentNode->layer);
  757. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  758. + carrierParentNode->moveRemains / (float)moveRemains;
  759. candidate.turns = otherParentNode->turns;
  760. candidate.setCost(candidate.getCost() + waitingCost);
  761. candidate.moveRemains = moveRemains;
  762. }
  763. return candidate;
  764. }
  765. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  766. {
  767. std::set<const CGHeroInstance *> heroes;
  768. for(auto actor : actors)
  769. {
  770. if(actor->hero)
  771. heroes.insert(actor->hero);
  772. }
  773. return heroes;
  774. }
  775. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  776. {
  777. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  778. {
  779. return true;
  780. }
  781. auto aiNode = getAINode(destination.node);
  782. if(heroChainPass != EHeroChainPass::CHAIN
  783. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  784. {
  785. return true;
  786. }
  787. return false;
  788. }
  789. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  790. {
  791. playerID = ai->playerID;
  792. for(auto & hero : heroes)
  793. {
  794. // do not allow our own heroes in garrison to act on map
  795. if(hero.first->getOwner() == ai->playerID
  796. && hero.first->isGarrisoned()
  797. && (ai->isHeroLocked(hero.first) || ai->heroManager->heroCapReached(false)))
  798. {
  799. continue;
  800. }
  801. uint64_t mask = FirstActorMask << actors.size();
  802. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
  803. if(actor->hero->tempOwner != ai->playerID)
  804. {
  805. bool onLand = !actor->hero->inBoat() || actor->hero->getBoat()->layer != EPathfindingLayer::SAIL;
  806. actor->initialMovement = actor->hero->movementPointsLimit(onLand);
  807. }
  808. playerID = actor->hero->tempOwner;
  809. actors.push_back(actor);
  810. }
  811. }
  812. void AINodeStorage::setTownsAndDwellings(
  813. const std::vector<const CGTownInstance *> & towns,
  814. const std::set<const CGObjectInstance *> & visitableObjs)
  815. {
  816. for(auto town : towns)
  817. {
  818. uint64_t mask = FirstActorMask << actors.size();
  819. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->getGarrisonHero()) != HeroLockedReason::DEFENCE
  820. // check defence imrove
  821. if(!town->getGarrisonHero())
  822. {
  823. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  824. }
  825. }
  826. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  827. auto waitForGrowth = dayOfWeek > 4;*/
  828. for(auto obj: visitableObjs)
  829. {
  830. if(obj->ID == Obj::HILL_FORT)
  831. {
  832. uint64_t mask = FirstActorMask << actors.size();
  833. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  834. }
  835. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  836. if(dwelling)
  837. {
  838. uint64_t mask = 1 << actors.size();
  839. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  840. if(dwellingActor->creatureSet->getArmyStrength())
  841. {
  842. actors.push_back(dwellingActor);
  843. }
  844. if(waitForGrowth)
  845. {
  846. mask = 1 << actors.size();
  847. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  848. if(dwellingActor->creatureSet->getArmyStrength())
  849. {
  850. actors.push_back(dwellingActor);
  851. }
  852. }
  853. }*/
  854. }
  855. }
  856. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  857. const PathNodeInfo & source,
  858. const PathfinderConfig * pathfinderConfig,
  859. const CPathfinderHelper * pathfinderHelper)
  860. {
  861. std::vector<CGPathNode *> neighbours;
  862. if(source.isNodeObjectVisitable())
  863. {
  864. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  865. auto srcNode = getAINode(source.node);
  866. for(auto & neighbour : accessibleExits)
  867. {
  868. std::optional<AIPathNode *> node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  869. if(!node)
  870. continue;
  871. neighbours.push_back(node.value());
  872. }
  873. }
  874. return neighbours;
  875. }
  876. struct TownPortalFinder
  877. {
  878. const std::vector<CGPathNode *> & initialNodes;
  879. MasteryLevel::Type townPortalSkillLevel;
  880. uint64_t movementNeeded;
  881. const ChainActor * actor;
  882. const CGHeroInstance * hero;
  883. std::vector<const CGTownInstance *> targetTowns;
  884. AINodeStorage * nodeStorage;
  885. SpellID spellID;
  886. const CSpell * townPortal;
  887. TownPortalFinder(
  888. const ChainActor * actor,
  889. const std::vector<CGPathNode *> & initialNodes,
  890. std::vector<const CGTownInstance *> targetTowns,
  891. AINodeStorage * nodeStorage)
  892. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  893. targetTowns(targetTowns), nodeStorage(nodeStorage)
  894. {
  895. spellID = SpellID::TOWN_PORTAL;
  896. townPortal = spellID.toSpell();
  897. // TODO: Copy/Paste from TownPortalMechanics
  898. townPortalSkillLevel = MasteryLevel::Type(hero->getSpellSchoolLevel(townPortal));
  899. int baseCost = hero->cb->getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  900. movementNeeded = baseCost * (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->getVisitingHero()
  979. && targetTown->getUpperArmy()->stacksCount()
  980. && maskMap.find(targetTown->getVisitingHero()) != maskMap.end())
  981. {
  982. auto basicMask = maskMap.at(targetTown->getVisitingHero());
  983. bool sameActorInTown = actor->chainMask == basicMask;
  984. if(!sameActorInTown)
  985. continue;
  986. }
  987. if (targetTown->getVisitingHero()
  988. && (targetTown->getVisitingHero()->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. }