AINodeStorage.cpp 42 KB

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