AINodeStorage.cpp 37 KB

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