AINodeStorage.cpp 36 KB

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