AINodeStorage.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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> committedTiles;
  29. std::set<int3> committedTilesInitial;
  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_COMMITTED_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. accessibility = 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. 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->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 saveToCommitted) 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. "Committed %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(saveToCommitted && destination->turns <= heroChainTurn)
  255. {
  256. committedTiles.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. committedTiles.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. committedTiles.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(committedTiles.begin(), committedTiles.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. committedTiles.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. committedTilesInitial = committedTiles;
  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. committedTiles = committedTilesInitial;
  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 inefficient",
  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 inefficient. 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_COMMITTED_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 TownPortalFinder
  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. TownPortalFinder(
  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_COMMITTED_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. TownPortalFinder 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. // TODO: re-enable after fixing thread races. See issue for details:
  993. // https://github.com/vcmi/vcmi/pull/4130
  994. #if 0
  995. if (actorsVector.size() * initialNodes.size() > 1000)
  996. {
  997. tbb::parallel_for(tbb::blocked_range<size_t>(0, actorsVector.size()), [&](const tbb::blocked_range<size_t> & r)
  998. {
  999. for(int i = r.begin(); i != r.end(); i++)
  1000. {
  1001. calculateTownPortal(actorsVector[i], maskMap, initialNodes, output);
  1002. }
  1003. });
  1004. std::copy(output.begin(), output.end(), std::back_inserter(initialNodes));
  1005. }
  1006. else
  1007. #endif
  1008. {
  1009. for(auto actor : actorsVector)
  1010. {
  1011. calculateTownPortal(actor, maskMap, initialNodes, initialNodes);
  1012. }
  1013. }
  1014. }
  1015. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  1016. {
  1017. auto candidateNode = getAINode(destination.node);
  1018. return hasBetterChain(source.node, *candidateNode);
  1019. }
  1020. bool AINodeStorage::hasBetterChain(
  1021. const CGPathNode * source,
  1022. const AIPathNode & candidateNode) const
  1023. {
  1024. return iterateValidNodesUntil(
  1025. candidateNode.coord,
  1026. candidateNode.layer,
  1027. [this, &source, candidateNode](const AIPathNode & node) -> bool
  1028. {
  1029. return isOtherChainBetter(source, candidateNode, node);
  1030. });
  1031. }
  1032. template<class NodeRange>
  1033. bool AINodeStorage::hasBetterChain(
  1034. const CGPathNode * source,
  1035. const AIPathNode & candidateNode,
  1036. const NodeRange & nodes) const
  1037. {
  1038. for(const AIPathNode & node : nodes)
  1039. {
  1040. if(isOtherChainBetter(source, candidateNode, node))
  1041. return true;
  1042. }
  1043. return false;
  1044. }
  1045. bool AINodeStorage::isOtherChainBetter(
  1046. const CGPathNode * source,
  1047. const AIPathNode & candidateNode,
  1048. const AIPathNode & other) const
  1049. {
  1050. auto sameNode = other.actor == candidateNode.actor;
  1051. if(sameNode || other.action == EPathNodeAction::UNKNOWN || !other.actor || !other.actor->hero)
  1052. {
  1053. return false;
  1054. }
  1055. if(other.danger <= candidateNode.danger && candidateNode.actor == other.actor->battleActor)
  1056. {
  1057. if(other.getCost() < candidateNode.getCost())
  1058. {
  1059. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1060. logAi->trace(
  1061. "Block inefficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1062. source->coord.toString(),
  1063. candidateNode.coord.toString(),
  1064. candidateNode.actor->hero->getNameTranslated(),
  1065. candidateNode.actor->chainMask,
  1066. candidateNode.actor->armyValue,
  1067. other.moveRemains - candidateNode.moveRemains);
  1068. #endif
  1069. return true;
  1070. }
  1071. }
  1072. if(candidateNode.actor->chainMask != other.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  1073. return false;
  1074. auto nodeActor = other.actor;
  1075. auto nodeArmyValue = nodeActor->armyValue - other.armyLoss;
  1076. auto candidateArmyValue = candidateNode.actor->armyValue - candidateNode.armyLoss;
  1077. if(nodeArmyValue > candidateArmyValue
  1078. && other.getCost() <= candidateNode.getCost())
  1079. {
  1080. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1081. logAi->trace(
  1082. "Block inefficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1083. source->coord.toString(),
  1084. candidateNode.coord.toString(),
  1085. candidateNode.actor->hero->getNameTranslated(),
  1086. candidateNode.actor->chainMask,
  1087. candidateNode.actor->armyValue,
  1088. other.moveRemains - candidateNode.moveRemains);
  1089. #endif
  1090. return true;
  1091. }
  1092. if(heroChainPass == EHeroChainPass::FINAL)
  1093. {
  1094. if(nodeArmyValue == candidateArmyValue
  1095. && nodeActor->heroFightingStrength >= candidateNode.actor->heroFightingStrength
  1096. && other.getCost() <= candidateNode.getCost())
  1097. {
  1098. if(vstd::isAlmostEqual(nodeActor->heroFightingStrength, candidateNode.actor->heroFightingStrength)
  1099. && vstd::isAlmostEqual(other.getCost(), candidateNode.getCost())
  1100. && &other < &candidateNode)
  1101. {
  1102. return false;
  1103. }
  1104. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1105. logAi->trace(
  1106. "Block inefficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1107. source->coord.toString(),
  1108. candidateNode.coord.toString(),
  1109. candidateNode.actor->hero->getNameTranslated(),
  1110. candidateNode.actor->chainMask,
  1111. candidateNode.actor->armyValue,
  1112. other.moveRemains - candidateNode.moveRemains);
  1113. #endif
  1114. return true;
  1115. }
  1116. }
  1117. return false;
  1118. }
  1119. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  1120. {
  1121. auto chains = nodes.get(pos);
  1122. for(const AIPathNode & node : chains)
  1123. {
  1124. if(node.version == AISharedStorage::version
  1125. && node.layer == layer
  1126. && node.action != EPathNodeAction::UNKNOWN
  1127. && node.actor
  1128. && node.actor->hero == hero.h)
  1129. {
  1130. return true;
  1131. }
  1132. }
  1133. return false;
  1134. }
  1135. void AINodeStorage::calculateChainInfo(std::vector<AIPath> & paths, const int3 & pos, bool isOnLand) const
  1136. {
  1137. auto layer = isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL;
  1138. auto chains = nodes.get(pos);
  1139. for(const AIPathNode & node : chains)
  1140. {
  1141. if(node.version != AISharedStorage::version
  1142. || node.layer != layer
  1143. || node.action == EPathNodeAction::UNKNOWN
  1144. || !node.actor
  1145. || !node.actor->hero)
  1146. {
  1147. continue;
  1148. }
  1149. AIPath & path = paths.emplace_back();
  1150. path.targetHero = node.actor->hero;
  1151. path.heroArmy = node.actor->creatureSet;
  1152. path.armyLoss = node.armyLoss;
  1153. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, !node.actor->allowBattle);
  1154. path.targetObjectArmyLoss = evaluateArmyLoss(
  1155. path.targetHero,
  1156. getHeroArmyStrengthWithCommander(path.targetHero, path.heroArmy),
  1157. path.targetObjectDanger);
  1158. path.chainMask = node.actor->chainMask;
  1159. path.exchangeCount = node.actor->actorExchangeCount;
  1160. fillChainInfo(&node, path, -1);
  1161. }
  1162. }
  1163. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  1164. {
  1165. while(node != nullptr)
  1166. {
  1167. if(!node->actor->hero)
  1168. return;
  1169. if(node->chainOther)
  1170. fillChainInfo(node->chainOther, path, parentIndex);
  1171. AIPathNodeInfo pathNode;
  1172. pathNode.cost = node->getCost();
  1173. pathNode.targetHero = node->actor->hero;
  1174. pathNode.chainMask = node->actor->chainMask;
  1175. pathNode.specialAction = node->specialAction;
  1176. pathNode.turns = node->turns;
  1177. pathNode.danger = node->danger;
  1178. pathNode.coord = node->coord;
  1179. pathNode.parentIndex = parentIndex;
  1180. pathNode.actionIsBlocked = false;
  1181. pathNode.layer = node->layer;
  1182. if(pathNode.specialAction)
  1183. {
  1184. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  1185. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(ai, targetNode);
  1186. }
  1187. parentIndex = path.nodes.size();
  1188. path.nodes.push_back(pathNode);
  1189. node = getAINode(node->theNodeBefore);
  1190. }
  1191. }
  1192. AIPath::AIPath()
  1193. : nodes({})
  1194. {
  1195. }
  1196. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  1197. {
  1198. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  1199. {
  1200. if(node->specialAction && node->actionIsBlocked)
  1201. return node->specialAction;
  1202. }
  1203. return std::shared_ptr<const SpecialAction>();
  1204. }
  1205. int3 AIPath::firstTileToGet() const
  1206. {
  1207. if(nodes.size())
  1208. {
  1209. return nodes.back().coord;
  1210. }
  1211. return int3(-1, -1, -1);
  1212. }
  1213. int3 AIPath::targetTile() const
  1214. {
  1215. if(nodes.size())
  1216. {
  1217. return targetNode().coord;
  1218. }
  1219. return int3(-1, -1, -1);
  1220. }
  1221. const AIPathNodeInfo & AIPath::firstNode() const
  1222. {
  1223. return nodes.back();
  1224. }
  1225. const AIPathNodeInfo & AIPath::targetNode() const
  1226. {
  1227. auto & node = nodes.front();
  1228. return targetHero == node.targetHero ? node : nodes.at(1);
  1229. }
  1230. uint64_t AIPath::getPathDanger() const
  1231. {
  1232. if(nodes.empty())
  1233. return 0;
  1234. return targetNode().danger;
  1235. }
  1236. float AIPath::movementCost() const
  1237. {
  1238. if(nodes.empty())
  1239. return 0.0f;
  1240. return targetNode().cost;
  1241. }
  1242. uint8_t AIPath::turn() const
  1243. {
  1244. if(nodes.empty())
  1245. return 0;
  1246. return targetNode().turns;
  1247. }
  1248. uint64_t AIPath::getHeroStrength() const
  1249. {
  1250. return targetHero->getFightingStrength() * getHeroArmyStrengthWithCommander(targetHero, heroArmy);
  1251. }
  1252. uint64_t AIPath::getTotalDanger() const
  1253. {
  1254. uint64_t pathDanger = getPathDanger();
  1255. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1256. return danger;
  1257. }
  1258. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1259. {
  1260. if(targetHero == hero)
  1261. return true;
  1262. for(auto node : nodes)
  1263. {
  1264. if(node.targetHero == hero)
  1265. return true;
  1266. }
  1267. return false;
  1268. }
  1269. uint64_t AIPath::getTotalArmyLoss() const
  1270. {
  1271. return armyLoss + targetObjectArmyLoss;
  1272. }
  1273. std::string AIPath::toString() const
  1274. {
  1275. std::stringstream str;
  1276. str << targetHero->getNameTranslated() << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1277. for(auto node : nodes)
  1278. str << node.targetHero->getNameTranslated() << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1279. return str.str();
  1280. }
  1281. }