AINodeStorage.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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 "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/PathfinderUtil.h"
  18. #include "../../../lib/CPlayerState.h"
  19. AINodeStorage::AINodeStorage(const int3 & Sizes)
  20. : sizes(Sizes)
  21. {
  22. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]);
  23. dangerEvaluator.reset(new FuzzyHelper());
  24. }
  25. AINodeStorage::~AINodeStorage() = default;
  26. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. if(heroChainPass)
  29. return;
  30. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  31. int3 pos;
  32. const PlayerColor player = ai->playerID;
  33. const int3 sizes = gs->getMapSize();
  34. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  35. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  36. const bool useFlying = options.useFlying;
  37. const bool useWaterWalking = options.useWaterWalking;
  38. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  39. {
  40. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  41. {
  42. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  43. {
  44. const TerrainTile * tile = &gs->map->getTile(pos);
  45. switch(tile->terType)
  46. {
  47. case ETerrainType::ROCK:
  48. break;
  49. case ETerrainType::WATER:
  50. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  51. if(useFlying)
  52. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  53. if(useWaterWalking)
  54. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  55. break;
  56. default:
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. void AINodeStorage::clear()
  67. {
  68. actors.clear();
  69. heroChainPass = false;
  70. heroChainTurn = 1;
  71. }
  72. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  73. {
  74. return static_cast<const AIPathNode *>(node);
  75. }
  76. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  77. {
  78. auto aiNode = static_cast<AIPathNode *>(node);
  79. updater(aiNode);
  80. }
  81. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  82. const int3 & pos,
  83. const EPathfindingLayer layer,
  84. const ChainActor * actor)
  85. {
  86. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  87. for(AIPathNode & node : chains)
  88. {
  89. if(node.actor == actor)
  90. {
  91. return &node;
  92. }
  93. if(!node.actor)
  94. {
  95. node.actor = actor;
  96. return &node;
  97. }
  98. }
  99. return boost::none;
  100. }
  101. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  102. {
  103. if(heroChainPass)
  104. return heroChain;
  105. std::vector<CGPathNode *> initialNodes;
  106. for(auto actorPtr : actors)
  107. {
  108. ChainActor * actor = actorPtr.get();
  109. AIPathNode * initialNode =
  110. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  111. .get();
  112. initialNode->turns = actor->initialTurn;
  113. initialNode->moveRemains = actor->initialMovement;
  114. initialNode->danger = 0;
  115. initialNode->cost = actor->initialTurn;
  116. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  117. if(actor->isMovable)
  118. {
  119. initialNodes.push_back(initialNode);
  120. }
  121. else
  122. {
  123. initialNode->locked = true;
  124. }
  125. }
  126. return initialNodes;
  127. }
  128. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  129. {
  130. for(int i = 0; i < NUM_CHAINS; i++)
  131. {
  132. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  133. heroNode.actor = nullptr;
  134. heroNode.danger = 0;
  135. heroNode.manaCost = 0;
  136. heroNode.specialAction.reset();
  137. heroNode.armyLoss = 0;
  138. heroNode.chainOther = nullptr;
  139. heroNode.update(coord, layer, accessibility);
  140. }
  141. }
  142. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  143. {
  144. const AIPathNode * srcNode = getAINode(source.node);
  145. updateAINode(destination.node, [&](AIPathNode * dstNode)
  146. {
  147. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  148. if(srcNode->specialAction || srcNode->chainOther)
  149. {
  150. // there is some action on source tile which should be performed before we can bypass it
  151. destination.node->theNodeBefore = source.node;
  152. }
  153. if(dstNode->specialAction && dstNode->actor)
  154. {
  155. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  156. }
  157. #if VCMI_TRACE_PATHFINDER >= 2
  158. logAi->trace(
  159. "Commited %s -> %s, cost: %f, hero: %s, mask: %x, army: %i",
  160. source.coord.toString(),
  161. destination.coord.toString(),
  162. destination.cost,
  163. dstNode->actor->toString(),
  164. dstNode->actor->chainMask,
  165. dstNode->actor->armyValue);
  166. #endif
  167. });
  168. }
  169. void AINodeStorage::commit(
  170. AIPathNode * destination,
  171. const AIPathNode * source,
  172. CGPathNode::ENodeAction action,
  173. int turn,
  174. int movementLeft,
  175. float cost) const
  176. {
  177. destination->action = action;
  178. destination->cost = cost;
  179. destination->moveRemains = movementLeft;
  180. destination->turns = turn;
  181. destination->armyLoss = source->armyLoss;
  182. destination->manaCost = source->manaCost;
  183. destination->danger = source->danger;
  184. destination->theNodeBefore = source->theNodeBefore;
  185. destination->chainOther = nullptr;
  186. }
  187. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  188. const PathNodeInfo & source,
  189. const PathfinderConfig * pathfinderConfig,
  190. const CPathfinderHelper * pathfinderHelper)
  191. {
  192. std::vector<CGPathNode *> neighbours;
  193. neighbours.reserve(16);
  194. const AIPathNode * srcNode = getAINode(source.node);
  195. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  196. for(auto & neighbour : accessibleNeighbourTiles)
  197. {
  198. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  199. {
  200. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  201. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  202. continue;
  203. neighbours.push_back(nextNode.get());
  204. }
  205. }
  206. return neighbours;
  207. }
  208. bool AINodeStorage::calculateHeroChain()
  209. {
  210. heroChainPass = true;
  211. heroChain.resize(0);
  212. std::vector<AIPathNode *> existingChains;
  213. std::vector<ExchangeCandidate> newChains;
  214. existingChains.reserve(NUM_CHAINS);
  215. newChains.reserve(NUM_CHAINS);
  216. foreach_tile_pos([&](const int3 & pos) {
  217. auto layer = EPathfindingLayer::LAND;
  218. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  219. existingChains.resize(0);
  220. newChains.resize(0);
  221. for(AIPathNode & node : chains)
  222. {
  223. if(node.coord.x == 60 && node.coord.y == 56 && node.actor)
  224. logAi->trace(node.actor->toString());
  225. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  226. existingChains.push_back(&node);
  227. }
  228. for(AIPathNode * node : existingChains)
  229. {
  230. if(node->actor->isMovable)
  231. {
  232. calculateHeroChain(node, existingChains, newChains);
  233. }
  234. }
  235. cleanupInefectiveChains(newChains);
  236. addHeroChain(newChains);
  237. });
  238. return heroChain.size();
  239. }
  240. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  241. {
  242. vstd::erase_if(result, [&](ExchangeCandidate & chainInfo) -> bool
  243. {
  244. auto pos = chainInfo.coord;
  245. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  246. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  247. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  248. });
  249. }
  250. void AINodeStorage::calculateHeroChain(
  251. AIPathNode * srcNode,
  252. const std::vector<AIPathNode *> & variants,
  253. std::vector<ExchangeCandidate> & result) const
  254. {
  255. for(AIPathNode * node : variants)
  256. {
  257. if(node == srcNode || !node->actor || node->turns > heroChainTurn
  258. || node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero
  259. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  260. {
  261. continue;
  262. }
  263. #if VCMI_TRACE_PATHFINDER >= 2
  264. logAi->trace(
  265. "Thy exchange %s[%i] -> %s[%i] at %s",
  266. node->actor->toString(),
  267. node->actor->chainMask,
  268. srcNode->actor->toString(),
  269. srcNode->actor->chainMask,
  270. srcNode->coord.toString());
  271. #endif
  272. calculateHeroChain(srcNode, node, result);
  273. }
  274. }
  275. void AINodeStorage::calculateHeroChain(
  276. AIPathNode * carrier,
  277. AIPathNode * other,
  278. std::vector<ExchangeCandidate> & result) const
  279. {
  280. if(carrier->actor->canExchange(other->actor))
  281. {
  282. #if VCMI_TRACE_PATHFINDER >= 2
  283. logAi->trace(
  284. "Exchange allowed %s[%i] -> %s[%i] at %s",
  285. other->actor->toString(),
  286. other->actor->chainMask,
  287. carrier->actor->toString(),
  288. carrier->actor->chainMask,
  289. carrier->coord.toString());
  290. #endif
  291. if(other->actor->isMovable)
  292. {
  293. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  294. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  295. if(hasLessMp && hasLessExperience)
  296. {
  297. #if VCMI_TRACE_PATHFINDER >= 2
  298. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  299. #endif
  300. return;
  301. }
  302. }
  303. auto newActor = carrier->actor->exchange(other->actor);
  304. result.push_back(calculateExchange(newActor, carrier, other));
  305. }
  306. }
  307. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  308. {
  309. for(const ExchangeCandidate & chainInfo : result)
  310. {
  311. auto carrier = chainInfo.carrierParent;
  312. auto newActor = chainInfo.actor;
  313. auto other = chainInfo.otherParent;
  314. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  315. if(!chainNodeOptional)
  316. {
  317. #if VCMI_TRACE_PATHFINDER >= 2
  318. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  319. #endif
  320. continue;
  321. }
  322. auto exchangeNode = chainNodeOptional.get();
  323. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  324. {
  325. #if VCMI_TRACE_PATHFINDER >= 2
  326. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  327. #endif
  328. continue;
  329. }
  330. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  331. {
  332. #if VCMI_TRACE_PATHFINDER >= 2
  333. logAi->trace(
  334. "Exchange at %s is is not effective enough. %f < %f",
  335. exchangeNode->coord.toString(),
  336. exchangeNode->cost,
  337. chainInfo.cost);
  338. #endif
  339. continue;
  340. }
  341. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  342. exchangeNode->chainOther = other;
  343. exchangeNode->armyLoss = chainInfo.armyLoss;
  344. #if VCMI_TRACE_PATHFINDER >= 2
  345. logAi->trace(
  346. "Chain accepted at %s %s -> %s, mask %x, cost %f, army %i",
  347. exchangeNode->coord.toString(),
  348. other->actor->toString(),
  349. exchangeNode->actor->toString(),
  350. exchangeNode->actor->chainMask,
  351. exchangeNode->cost,
  352. exchangeNode->actor->armyValue);
  353. #endif
  354. heroChain.push_back(exchangeNode);
  355. }
  356. }
  357. ExchangeCandidate AINodeStorage::calculateExchange(
  358. ChainActor * exchangeActor,
  359. AIPathNode * carrierParentNode,
  360. AIPathNode * otherParentNode) const
  361. {
  362. ExchangeCandidate candidate;
  363. auto carrierActor = carrierParentNode->actor;
  364. auto otherActor = otherParentNode->actor;
  365. candidate.layer = carrierParentNode->layer;
  366. candidate.coord = carrierParentNode->coord;
  367. candidate.carrierParent = carrierParentNode;
  368. candidate.otherParent = otherParentNode;
  369. candidate.actor = exchangeActor;
  370. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  371. candidate.turns = carrierParentNode->turns;
  372. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  373. candidate.moveRemains = carrierParentNode->moveRemains;
  374. if(carrierParentNode->turns < otherParentNode->turns)
  375. {
  376. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  377. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  378. + carrierParentNode->moveRemains / (float)moveRemains;
  379. candidate.turns = otherParentNode->turns;
  380. candidate.cost += waitingCost;
  381. candidate.moveRemains = moveRemains;
  382. }
  383. return candidate;
  384. }
  385. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  386. {
  387. auto aiNode = getAINode(node);
  388. return aiNode->actor->hero;
  389. }
  390. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  391. {
  392. std::set<const CGHeroInstance *> heroes;
  393. for(auto actor : actors)
  394. {
  395. if(actor->hero)
  396. heroes.insert(actor->hero);
  397. }
  398. return heroes;
  399. }
  400. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  401. {
  402. cb = _ai->myCb.get();
  403. ai = _ai;
  404. for(auto & hero : heroes)
  405. {
  406. uint64_t mask = 1 << actors.size();
  407. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask, ai));
  408. }
  409. }
  410. void AINodeStorage::setTownsAndDwellings(
  411. const std::vector<const CGTownInstance *> & towns,
  412. const std::set<const CGObjectInstance *> & visitableObjs)
  413. {
  414. for(auto town : towns)
  415. {
  416. uint64_t mask = 1 << actors.size();
  417. if(town->getUpperArmy()->getArmyStrength())
  418. {
  419. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  420. }
  421. }
  422. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  423. auto waitForGrowth = dayOfWeek > 4;
  424. for(auto obj: visitableObjs)
  425. {
  426. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  427. if(dwelling)
  428. {
  429. uint64_t mask = 1 << actors.size();
  430. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  431. if(dwellingActor->creatureSet->getArmyStrength())
  432. {
  433. actors.push_back(dwellingActor);
  434. }
  435. if(waitForGrowth)
  436. {
  437. mask = 1 << actors.size();
  438. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  439. if(dwellingActor->creatureSet->getArmyStrength())
  440. {
  441. actors.push_back(dwellingActor);
  442. }
  443. }
  444. }
  445. }*/
  446. }
  447. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  448. const PathNodeInfo & source,
  449. const PathfinderConfig * pathfinderConfig,
  450. const CPathfinderHelper * pathfinderHelper)
  451. {
  452. std::vector<CGPathNode *> neighbours;
  453. if(source.isNodeObjectVisitable())
  454. {
  455. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  456. auto srcNode = getAINode(source.node);
  457. for(auto & neighbour : accessibleExits)
  458. {
  459. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  460. if(!node)
  461. continue;
  462. neighbours.push_back(node.get());
  463. }
  464. }
  465. if(source.isInitialPosition)
  466. {
  467. calculateTownPortalTeleportations(source, neighbours);
  468. }
  469. return neighbours;
  470. }
  471. void AINodeStorage::calculateTownPortalTeleportations(
  472. const PathNodeInfo & source,
  473. std::vector<CGPathNode *> & neighbours)
  474. {
  475. SpellID spellID = SpellID::TOWN_PORTAL;
  476. const CSpell * townPortal = spellID.toSpell();
  477. auto srcNode = getAINode(source.node);
  478. auto hero = srcNode->actor->hero;
  479. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  480. {
  481. auto towns = cb->getTownsInfo(false);
  482. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  483. {
  484. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  485. });
  486. if(!towns.size())
  487. {
  488. return;
  489. }
  490. // TODO: Copy/Paste from TownPortalMechanics
  491. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  492. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  493. if(hero->movement < movementCost)
  494. {
  495. return;
  496. }
  497. if(skillLevel < SecSkillLevel::ADVANCED)
  498. {
  499. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  500. {
  501. return hero->visitablePos().dist2dSQ(t->visitablePos());
  502. });
  503. towns = std::vector<const CGTownInstance *>{ nearestTown };
  504. }
  505. for(const CGTownInstance * targetTown : towns)
  506. {
  507. if(targetTown->visitingHero)
  508. continue;
  509. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  510. if(nodeOptional)
  511. {
  512. #ifdef VCMI_TRACE_PATHFINDER
  513. logAi->trace("Adding town portal node at %s", targetTown->name);
  514. #endif
  515. AIPathNode * node = nodeOptional.get();
  516. node->theNodeBefore = source.node;
  517. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  518. node->moveRemains = source.node->moveRemains;
  519. neighbours.push_back(node);
  520. }
  521. }
  522. }
  523. }
  524. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  525. {
  526. auto pos = destination.coord;
  527. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  528. return hasBetterChain(source.node, getAINode(destination.node), chains);
  529. }
  530. template<class NodeRange>
  531. bool AINodeStorage::hasBetterChain(
  532. const CGPathNode * source,
  533. const AIPathNode * candidateNode,
  534. const NodeRange & chains) const
  535. {
  536. auto candidateActor = candidateNode->actor;
  537. for(const AIPathNode & node : chains)
  538. {
  539. auto sameNode = node.actor == candidateNode->actor;
  540. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  541. {
  542. continue;
  543. }
  544. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  545. {
  546. if(node.cost < candidateNode->cost)
  547. {
  548. #ifdef VCMI_TRACE_PATHFINDER
  549. logAi->trace(
  550. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  551. source->coord.toString(),
  552. candidateNode->coord.toString(),
  553. candidateNode->actor->chainMask,
  554. node.moveRemains - candidateNode->moveRemains);
  555. #endif
  556. return true;
  557. }
  558. }
  559. if(candidateActor->actorExchangeCount == 1
  560. && (candidateActor->chainMask & node.actor->chainMask) == 0)
  561. continue;
  562. auto nodeActor = node.actor;
  563. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  564. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  565. if(nodeArmyValue > candidateArmyValue
  566. && node.cost <= candidateNode->cost)
  567. {
  568. return true;
  569. }
  570. if(nodeArmyValue == candidateArmyValue
  571. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  572. && node.cost <= candidateNode->cost)
  573. {
  574. return true;
  575. }
  576. }
  577. return false;
  578. }
  579. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  580. {
  581. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  582. for(const AIPathNode & node : chains)
  583. {
  584. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  585. && node.actor && node.actor->hero == hero.h)
  586. {
  587. return true;
  588. }
  589. }
  590. return false;
  591. }
  592. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  593. {
  594. std::vector<AIPath> paths;
  595. paths.reserve(NUM_CHAINS / 4);
  596. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  597. for(const AIPathNode & node : chains)
  598. {
  599. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  600. {
  601. continue;
  602. }
  603. AIPath path;
  604. path.targetHero = node.actor->hero;
  605. path.heroArmy = node.actor->creatureSet;
  606. path.armyLoss = node.armyLoss;
  607. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  608. path.chainMask = node.actor->chainMask;
  609. fillChainInfo(&node, path, -1);
  610. paths.push_back(path);
  611. }
  612. return paths;
  613. }
  614. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  615. {
  616. while(node != nullptr)
  617. {
  618. if(!node->actor->hero)
  619. return;
  620. if(node->chainOther)
  621. fillChainInfo(node->chainOther, path, parentIndex);
  622. if(node->actor->hero->visitablePos() != node->coord)
  623. {
  624. AIPathNodeInfo pathNode;
  625. pathNode.cost = node->cost;
  626. pathNode.targetHero = node->actor->hero;
  627. pathNode.turns = node->turns;
  628. pathNode.danger = node->danger;
  629. pathNode.coord = node->coord;
  630. pathNode.parentIndex = parentIndex;
  631. parentIndex = path.nodes.size();
  632. path.nodes.push_back(pathNode);
  633. }
  634. path.specialAction = node->specialAction;
  635. node = getAINode(node->theNodeBefore);
  636. }
  637. }
  638. AIPath::AIPath()
  639. : nodes({})
  640. {
  641. }
  642. int3 AIPath::firstTileToGet() const
  643. {
  644. if(nodes.size())
  645. {
  646. return nodes.back().coord;
  647. }
  648. return int3(-1, -1, -1);
  649. }
  650. int3 AIPath::targetTile() const
  651. {
  652. if(nodes.size())
  653. {
  654. return nodes.front().coord;
  655. }
  656. return int3(-1, -1, -1);
  657. }
  658. const AIPathNodeInfo & AIPath::firstNode() const
  659. {
  660. return nodes.back();
  661. }
  662. uint64_t AIPath::getPathDanger() const
  663. {
  664. if(nodes.size())
  665. {
  666. return nodes.front().danger;
  667. }
  668. return 0;
  669. }
  670. float AIPath::movementCost() const
  671. {
  672. if(nodes.size())
  673. {
  674. return nodes.front().cost;
  675. }
  676. // TODO: boost:optional?
  677. return 0.0;
  678. }
  679. uint64_t AIPath::getHeroStrength() const
  680. {
  681. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  682. }
  683. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  684. {
  685. uint64_t pathDanger = getPathDanger();
  686. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  687. return danger;
  688. }
  689. std::string AIPath::toString()
  690. {
  691. std::stringstream str;
  692. for(auto node : nodes)
  693. str << node.targetHero->name << "->" << node.coord.toString() << "; ";
  694. return str.str();
  695. }