AINodeStorage.cpp 30 KB

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