AINodeStorage.cpp 37 KB

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