AINodeStorage.cpp 38 KB

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