AINodeStorage.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. if(carrierParentNode->turns < otherParentNode->turns)
  708. {
  709. int moveRemains = exchangeActor->maxMovePoints(carrierParentNode->layer);
  710. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  711. + carrierParentNode->moveRemains / (float)moveRemains;
  712. candidate.turns = otherParentNode->turns;
  713. candidate.setCost(candidate.getCost() + waitingCost);
  714. candidate.moveRemains = moveRemains;
  715. }
  716. return candidate;
  717. }
  718. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  719. {
  720. std::set<const CGHeroInstance *> heroes;
  721. for(auto actor : actors)
  722. {
  723. if(actor->hero)
  724. heroes.insert(actor->hero);
  725. }
  726. return heroes;
  727. }
  728. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  729. {
  730. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  731. {
  732. return true;
  733. }
  734. auto aiNode = getAINode(destination.node);
  735. if(heroChainPass != EHeroChainPass::CHAIN
  736. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  737. {
  738. return true;
  739. }
  740. return false;
  741. }
  742. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  743. {
  744. playerID = ai->playerID;
  745. for(auto & hero : heroes)
  746. {
  747. // do not allow our own heroes in garrison to act on map
  748. if(hero.first->getOwner() == ai->playerID
  749. && hero.first->inTownGarrison
  750. && (ai->isHeroLocked(hero.first) || ai->heroManager->heroCapReached()))
  751. {
  752. continue;
  753. }
  754. uint64_t mask = FirstActorMask << actors.size();
  755. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
  756. if(actor->hero->tempOwner != ai->playerID)
  757. {
  758. bool onLand = !actor->hero->boat || actor->hero->boat->layer != EPathfindingLayer::SAIL;
  759. actor->initialMovement = actor->hero->movementPointsLimit(onLand);
  760. }
  761. playerID = actor->hero->tempOwner;
  762. actors.push_back(actor);
  763. }
  764. }
  765. void AINodeStorage::setTownsAndDwellings(
  766. const std::vector<const CGTownInstance *> & towns,
  767. const std::set<const CGObjectInstance *> & visitableObjs)
  768. {
  769. for(auto town : towns)
  770. {
  771. uint64_t mask = FirstActorMask << actors.size();
  772. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
  773. // check defence imrove
  774. if(!town->garrisonHero)
  775. {
  776. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  777. }
  778. }
  779. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  780. auto waitForGrowth = dayOfWeek > 4;*/
  781. for(auto obj: visitableObjs)
  782. {
  783. if(obj->ID == Obj::HILL_FORT)
  784. {
  785. uint64_t mask = FirstActorMask << actors.size();
  786. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  787. }
  788. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  789. if(dwelling)
  790. {
  791. uint64_t mask = 1 << actors.size();
  792. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  793. if(dwellingActor->creatureSet->getArmyStrength())
  794. {
  795. actors.push_back(dwellingActor);
  796. }
  797. if(waitForGrowth)
  798. {
  799. mask = 1 << actors.size();
  800. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  801. if(dwellingActor->creatureSet->getArmyStrength())
  802. {
  803. actors.push_back(dwellingActor);
  804. }
  805. }
  806. }*/
  807. }
  808. }
  809. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  810. const PathNodeInfo & source,
  811. const PathfinderConfig * pathfinderConfig,
  812. const CPathfinderHelper * pathfinderHelper)
  813. {
  814. std::vector<CGPathNode *> neighbours;
  815. if(source.isNodeObjectVisitable())
  816. {
  817. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  818. auto srcNode = getAINode(source.node);
  819. for(auto & neighbour : accessibleExits)
  820. {
  821. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  822. if(!node)
  823. continue;
  824. neighbours.push_back(node.value());
  825. }
  826. }
  827. return neighbours;
  828. }
  829. struct TowmPortalFinder
  830. {
  831. const std::vector<CGPathNode *> & initialNodes;
  832. MasteryLevel::Type townPortalSkillLevel;
  833. uint64_t movementNeeded;
  834. const ChainActor * actor;
  835. const CGHeroInstance * hero;
  836. std::vector<const CGTownInstance *> targetTowns;
  837. AINodeStorage * nodeStorage;
  838. SpellID spellID;
  839. const CSpell * townPortal;
  840. TowmPortalFinder(
  841. const ChainActor * actor,
  842. const std::vector<CGPathNode *> & initialNodes,
  843. std::vector<const CGTownInstance *> targetTowns,
  844. AINodeStorage * nodeStorage)
  845. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  846. targetTowns(targetTowns), nodeStorage(nodeStorage)
  847. {
  848. spellID = SpellID::TOWN_PORTAL;
  849. townPortal = spellID.toSpell();
  850. // TODO: Copy/Paste from TownPortalMechanics
  851. townPortalSkillLevel = MasteryLevel::Type(hero->getSpellSchoolLevel(townPortal));
  852. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= MasteryLevel::EXPERT ? 2 : 3);
  853. }
  854. bool actorCanCastTownPortal()
  855. {
  856. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  857. }
  858. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  859. {
  860. for(CGPathNode * node : initialNodes)
  861. {
  862. auto aiNode = nodeStorage->getAINode(node);
  863. if(aiNode->actor->baseActor != actor
  864. || node->layer != EPathfindingLayer::LAND
  865. || node->moveRemains < movementNeeded)
  866. {
  867. continue;
  868. }
  869. if(townPortalSkillLevel < MasteryLevel::ADVANCED)
  870. {
  871. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  872. {
  873. return node->coord.dist2dSQ(t->visitablePos());
  874. });
  875. if(targetTown != nearestTown)
  876. continue;
  877. }
  878. return node;
  879. }
  880. return nullptr;
  881. }
  882. std::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  883. {
  884. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  885. if(!bestNode)
  886. return std::nullopt;
  887. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  888. if(!nodeOptional)
  889. return std::nullopt;
  890. AIPathNode * node = nodeOptional.value();
  891. float movementCost = (float)movementNeeded / (float)hero->movementPointsLimit(EPathfindingLayer::LAND);
  892. movementCost += bestNode->getCost();
  893. if(node->action == EPathNodeAction::UNKNOWN || node->getCost() > movementCost)
  894. {
  895. nodeStorage->commit(
  896. node,
  897. nodeStorage->getAINode(bestNode),
  898. EPathNodeAction::TELEPORT_NORMAL,
  899. bestNode->turns,
  900. bestNode->moveRemains - movementNeeded,
  901. movementCost,
  902. DO_NOT_SAVE_TO_COMMITED_TILES);
  903. node->theNodeBefore = bestNode;
  904. node->addSpecialAction(std::make_shared<AIPathfinding::TownPortalAction>(targetTown));
  905. }
  906. return nodeOptional;
  907. }
  908. };
  909. template<class TVector>
  910. void AINodeStorage::calculateTownPortal(
  911. const ChainActor * actor,
  912. const std::map<const CGHeroInstance *, int> & maskMap,
  913. const std::vector<CGPathNode *> & initialNodes,
  914. TVector & output)
  915. {
  916. auto towns = cb->getTownsInfo(false);
  917. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  918. {
  919. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  920. });
  921. if(!towns.size())
  922. {
  923. return; // no towns no need to run loop further
  924. }
  925. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  926. if(townPortalFinder.actorCanCastTownPortal())
  927. {
  928. for(const CGTownInstance * targetTown : towns)
  929. {
  930. // TODO: allow to hide visiting hero in garrison
  931. if(targetTown->visitingHero && maskMap.find(targetTown->visitingHero.get()) != maskMap.end())
  932. {
  933. auto basicMask = maskMap.at(targetTown->visitingHero.get());
  934. bool heroIsInChain = (actor->chainMask & basicMask) != 0;
  935. bool sameActorInTown = actor->chainMask == basicMask;
  936. if(sameActorInTown || !heroIsInChain)
  937. continue;
  938. }
  939. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  940. if(nodeOptional)
  941. {
  942. #if NKAI_PATHFINDER_TRACE_LEVEL >= 1
  943. logAi->trace("Adding town portal node at %s", targetTown->getObjectName());
  944. #endif
  945. output.push_back(nodeOptional.value());
  946. }
  947. }
  948. }
  949. }
  950. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  951. {
  952. std::set<const ChainActor *> actorsOfInitial;
  953. for(const CGPathNode * node : initialNodes)
  954. {
  955. auto aiNode = getAINode(node);
  956. if(aiNode->actor->hero)
  957. actorsOfInitial.insert(aiNode->actor->baseActor);
  958. }
  959. std::map<const CGHeroInstance *, int> maskMap;
  960. for(std::shared_ptr<ChainActor> basicActor : actors)
  961. {
  962. if(basicActor->hero)
  963. maskMap[basicActor->hero] = basicActor->chainMask;
  964. }
  965. boost::sort(initialNodes, NodeComparer<CGPathNode>());
  966. std::vector<const ChainActor *> actorsVector(actorsOfInitial.begin(), actorsOfInitial.end());
  967. tbb::concurrent_vector<CGPathNode *> output;
  968. if(actorsVector.size() * initialNodes.size() > 1000)
  969. {
  970. parallel_for(blocked_range<size_t>(0, actorsVector.size()), [&](const blocked_range<size_t> & r)
  971. {
  972. for(int i = r.begin(); i != r.end(); i++)
  973. {
  974. calculateTownPortal(actorsVector[i], maskMap, initialNodes, output);
  975. }
  976. });
  977. std::copy(output.begin(), output.end(), std::back_inserter(initialNodes));
  978. }
  979. else
  980. {
  981. for(auto actor : actorsVector)
  982. {
  983. calculateTownPortal(actor, maskMap, initialNodes, initialNodes);
  984. }
  985. }
  986. }
  987. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  988. {
  989. auto pos = destination.coord;
  990. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  991. return hasBetterChain(source.node, getAINode(destination.node), chains);
  992. }
  993. template<class NodeRange>
  994. bool AINodeStorage::hasBetterChain(
  995. const CGPathNode * source,
  996. const AIPathNode * candidateNode,
  997. const NodeRange & chains) const
  998. {
  999. auto candidateActor = candidateNode->actor;
  1000. for(const AIPathNode & node : chains)
  1001. {
  1002. auto sameNode = node.actor == candidateNode->actor;
  1003. if(sameNode || node.action == EPathNodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  1004. {
  1005. continue;
  1006. }
  1007. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  1008. {
  1009. if(node.getCost() < candidateNode->getCost())
  1010. {
  1011. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1012. logAi->trace(
  1013. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1014. source->coord.toString(),
  1015. candidateNode->coord.toString(),
  1016. candidateNode->actor->hero->getNameTranslated(),
  1017. candidateNode->actor->chainMask,
  1018. candidateNode->actor->armyValue,
  1019. node.moveRemains - candidateNode->moveRemains);
  1020. #endif
  1021. return true;
  1022. }
  1023. }
  1024. if(candidateActor->chainMask != node.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  1025. continue;
  1026. auto nodeActor = node.actor;
  1027. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  1028. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  1029. if(nodeArmyValue > candidateArmyValue
  1030. && node.getCost() <= candidateNode->getCost())
  1031. {
  1032. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1033. logAi->trace(
  1034. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1035. source->coord.toString(),
  1036. candidateNode->coord.toString(),
  1037. candidateNode->actor->hero->getNameTranslated(),
  1038. candidateNode->actor->chainMask,
  1039. candidateNode->actor->armyValue,
  1040. node.moveRemains - candidateNode->moveRemains);
  1041. #endif
  1042. return true;
  1043. }
  1044. if(heroChainPass == EHeroChainPass::FINAL)
  1045. {
  1046. if(nodeArmyValue == candidateArmyValue
  1047. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  1048. && node.getCost() <= candidateNode->getCost())
  1049. {
  1050. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  1051. && node.getCost() == candidateNode->getCost()
  1052. && &node < candidateNode)
  1053. {
  1054. continue;
  1055. }
  1056. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1057. logAi->trace(
  1058. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1059. source->coord.toString(),
  1060. candidateNode->coord.toString(),
  1061. candidateNode->actor->hero->getNameTranslated(),
  1062. candidateNode->actor->chainMask,
  1063. candidateNode->actor->armyValue,
  1064. node.moveRemains - candidateNode->moveRemains);
  1065. #endif
  1066. return true;
  1067. }
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  1073. {
  1074. auto chains = nodes.get(pos, layer);
  1075. for(const AIPathNode & node : chains)
  1076. {
  1077. if(node.action != EPathNodeAction::UNKNOWN
  1078. && node.actor && node.actor->hero == hero.h)
  1079. {
  1080. return true;
  1081. }
  1082. }
  1083. return false;
  1084. }
  1085. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  1086. {
  1087. std::vector<AIPath> paths;
  1088. paths.reserve(AIPathfinding::NUM_CHAINS / 4);
  1089. auto chains = nodes.get(pos, isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  1090. for(const AIPathNode & node : chains)
  1091. {
  1092. if(node.action == EPathNodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  1093. {
  1094. continue;
  1095. }
  1096. AIPath path;
  1097. path.targetHero = node.actor->hero;
  1098. path.heroArmy = node.actor->creatureSet;
  1099. path.armyLoss = node.armyLoss;
  1100. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, !node.actor->allowBattle);
  1101. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  1102. path.chainMask = node.actor->chainMask;
  1103. path.exchangeCount = node.actor->actorExchangeCount;
  1104. fillChainInfo(&node, path, -1);
  1105. paths.push_back(path);
  1106. }
  1107. return paths;
  1108. }
  1109. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  1110. {
  1111. while(node != nullptr)
  1112. {
  1113. if(!node->actor->hero)
  1114. return;
  1115. if(node->chainOther)
  1116. fillChainInfo(node->chainOther, path, parentIndex);
  1117. //if(node->actor->hero->visitablePos() != node->coord)
  1118. {
  1119. AIPathNodeInfo pathNode;
  1120. pathNode.cost = node->getCost();
  1121. pathNode.targetHero = node->actor->hero;
  1122. pathNode.chainMask = node->actor->chainMask;
  1123. pathNode.specialAction = node->specialAction;
  1124. pathNode.turns = node->turns;
  1125. pathNode.danger = node->danger;
  1126. pathNode.coord = node->coord;
  1127. pathNode.parentIndex = parentIndex;
  1128. pathNode.actionIsBlocked = false;
  1129. pathNode.layer = node->layer;
  1130. if(pathNode.specialAction)
  1131. {
  1132. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  1133. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(targetNode);
  1134. }
  1135. parentIndex = path.nodes.size();
  1136. path.nodes.push_back(pathNode);
  1137. }
  1138. node = getAINode(node->theNodeBefore);
  1139. }
  1140. }
  1141. AIPath::AIPath()
  1142. : nodes({})
  1143. {
  1144. }
  1145. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  1146. {
  1147. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  1148. {
  1149. if(node->specialAction && node->actionIsBlocked)
  1150. return node->specialAction;
  1151. }
  1152. return std::shared_ptr<const SpecialAction>();
  1153. }
  1154. int3 AIPath::firstTileToGet() const
  1155. {
  1156. if(nodes.size())
  1157. {
  1158. return nodes.back().coord;
  1159. }
  1160. return int3(-1, -1, -1);
  1161. }
  1162. int3 AIPath::targetTile() const
  1163. {
  1164. if(nodes.size())
  1165. {
  1166. return targetNode().coord;
  1167. }
  1168. return int3(-1, -1, -1);
  1169. }
  1170. const AIPathNodeInfo & AIPath::firstNode() const
  1171. {
  1172. return nodes.back();
  1173. }
  1174. const AIPathNodeInfo & AIPath::targetNode() const
  1175. {
  1176. auto & node = nodes.front();
  1177. return targetHero == node.targetHero ? node : nodes.at(1);
  1178. }
  1179. uint64_t AIPath::getPathDanger() const
  1180. {
  1181. if(nodes.empty())
  1182. return 0;
  1183. return targetNode().danger;
  1184. }
  1185. float AIPath::movementCost() const
  1186. {
  1187. if(nodes.empty())
  1188. return 0.0f;
  1189. return targetNode().cost;
  1190. }
  1191. uint8_t AIPath::turn() const
  1192. {
  1193. if(nodes.empty())
  1194. return 0;
  1195. return targetNode().turns;
  1196. }
  1197. uint64_t AIPath::getHeroStrength() const
  1198. {
  1199. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  1200. }
  1201. uint64_t AIPath::getTotalDanger() const
  1202. {
  1203. uint64_t pathDanger = getPathDanger();
  1204. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1205. return danger;
  1206. }
  1207. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1208. {
  1209. if(targetHero == hero)
  1210. return true;
  1211. for(auto node : nodes)
  1212. {
  1213. if(node.targetHero == hero)
  1214. return true;
  1215. }
  1216. return false;
  1217. }
  1218. uint64_t AIPath::getTotalArmyLoss() const
  1219. {
  1220. return armyLoss + targetObjectArmyLoss;
  1221. }
  1222. std::string AIPath::toString() const
  1223. {
  1224. std::stringstream str;
  1225. str << targetHero->getNameTranslated() << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1226. for(auto node : nodes)
  1227. str << node.targetHero->getNameTranslated() << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1228. return str.str();
  1229. }
  1230. }