AINodeStorage.cpp 37 KB

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