AINodeStorage.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][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. parallel_for(blocked_range<size_t>(0, sizes.x), [&](const blocked_range<size_t>& r)
  65. {
  66. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  67. const bool useFlying = options.useFlying;
  68. const bool useWaterWalking = options.useWaterWalking;
  69. const PlayerColor player = playerID;
  70. int3 pos;
  71. for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
  72. {
  73. for(pos.y = 0; pos.y < sizes.y; ++pos.y)
  74. {
  75. for(pos.z = 0; pos.z < sizes.z; ++pos.z)
  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);
  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. }