AINodeStorage.cpp 41 KB

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