AINodeStorage.cpp 36 KB

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