AINodeStorage.cpp 30 KB

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