AINodeStorage.cpp 23 KB

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