AINodeStorage.cpp 37 KB

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