AINodeStorage.cpp 38 KB

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