AINodeStorage.cpp 39 KB

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