AINodeStorage.cpp 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. });
  163. }
  164. void AINodeStorage::commit(
  165. AIPathNode * destination,
  166. const AIPathNode * source,
  167. CGPathNode::ENodeAction action,
  168. int turn,
  169. int movementLeft,
  170. float cost) const
  171. {
  172. if(destination->actor->chainMask == 195 && turn == 0)
  173. {
  174. throw std::exception();
  175. }
  176. destination->action = action;
  177. destination->cost = cost;
  178. destination->moveRemains = movementLeft;
  179. destination->turns = turn;
  180. destination->armyLoss = source->armyLoss;
  181. destination->manaCost = source->manaCost;
  182. destination->danger = source->danger;
  183. destination->theNodeBefore = source->theNodeBefore;
  184. destination->chainOther = nullptr;
  185. #if AI_TRACE_LEVEL >= 2
  186. logAi->trace(
  187. "Commited %s -> %s, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  188. source->coord.toString(),
  189. destination->coord.toString(),
  190. destination->cost,
  191. std::to_string(destination->turns),
  192. destination->moveRemains,
  193. destination->actor->toString(),
  194. destination->actor->chainMask,
  195. destination->actor->armyValue);
  196. #endif
  197. }
  198. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  199. const PathNodeInfo & source,
  200. const PathfinderConfig * pathfinderConfig,
  201. const CPathfinderHelper * pathfinderHelper)
  202. {
  203. std::vector<CGPathNode *> neighbours;
  204. neighbours.reserve(16);
  205. const AIPathNode * srcNode = getAINode(source.node);
  206. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  207. for(auto & neighbour : accessibleNeighbourTiles)
  208. {
  209. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  210. {
  211. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  212. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  213. continue;
  214. neighbours.push_back(nextNode.get());
  215. }
  216. }
  217. return neighbours;
  218. }
  219. bool AINodeStorage::calculateHeroChain()
  220. {
  221. heroChainPass = true;
  222. heroChain.resize(0);
  223. std::vector<AIPathNode *> existingChains;
  224. std::vector<ExchangeCandidate> newChains;
  225. existingChains.reserve(NUM_CHAINS);
  226. newChains.reserve(NUM_CHAINS);
  227. foreach_tile_pos([&](const int3 & pos) {
  228. auto layer = EPathfindingLayer::LAND;
  229. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  230. existingChains.resize(0);
  231. newChains.resize(0);
  232. for(AIPathNode & node : chains)
  233. {
  234. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  235. existingChains.push_back(&node);
  236. }
  237. for(AIPathNode * node : existingChains)
  238. {
  239. if(node->actor->isMovable)
  240. {
  241. calculateHeroChain(node, existingChains, newChains);
  242. }
  243. }
  244. cleanupInefectiveChains(newChains);
  245. addHeroChain(newChains);
  246. });
  247. return heroChain.size();
  248. }
  249. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  250. {
  251. vstd::erase_if(result, [&](ExchangeCandidate & chainInfo) -> bool
  252. {
  253. auto pos = chainInfo.coord;
  254. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  255. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  256. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  257. });
  258. }
  259. void AINodeStorage::calculateHeroChain(
  260. AIPathNode * srcNode,
  261. const std::vector<AIPathNode *> & variants,
  262. std::vector<ExchangeCandidate> & result) const
  263. {
  264. for(AIPathNode * node : variants)
  265. {
  266. if(node == srcNode
  267. || !node->actor
  268. || node->turns > heroChainTurn
  269. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  270. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  271. {
  272. continue;
  273. }
  274. #if AI_TRACE_LEVEL >= 2
  275. logAi->trace(
  276. "Thy exchange %s[%x] -> %s[%x] at %s",
  277. node->actor->toString(),
  278. node->actor->chainMask,
  279. srcNode->actor->toString(),
  280. srcNode->actor->chainMask,
  281. srcNode->coord.toString());
  282. #endif
  283. calculateHeroChain(srcNode, node, result);
  284. }
  285. }
  286. void AINodeStorage::calculateHeroChain(
  287. AIPathNode * carrier,
  288. AIPathNode * other,
  289. std::vector<ExchangeCandidate> & result) const
  290. {
  291. if(carrier->armyLoss < carrier->actor->armyValue
  292. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  293. && carrier->action != CGPathNode::BLOCKING_VISIT
  294. && other->armyLoss < other->actor->armyValue
  295. && carrier->actor->canExchange(other->actor))
  296. {
  297. #if AI_TRACE_LEVEL >= 2
  298. logAi->trace(
  299. "Exchange allowed %s[%x] -> %s[%x] at %s",
  300. other->actor->toString(),
  301. other->actor->chainMask,
  302. carrier->actor->toString(),
  303. carrier->actor->chainMask,
  304. carrier->coord.toString());
  305. #endif
  306. if(other->actor->isMovable)
  307. {
  308. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  309. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  310. if(hasLessMp && hasLessExperience)
  311. {
  312. #if AI_TRACE_LEVEL >= 2
  313. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  314. #endif
  315. return;
  316. }
  317. }
  318. auto newActor = carrier->actor->exchange(other->actor);
  319. result.push_back(calculateExchange(newActor, carrier, other));
  320. }
  321. }
  322. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  323. {
  324. for(const ExchangeCandidate & chainInfo : result)
  325. {
  326. auto carrier = chainInfo.carrierParent;
  327. auto newActor = chainInfo.actor;
  328. auto other = chainInfo.otherParent;
  329. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  330. if(!chainNodeOptional)
  331. {
  332. #if AI_TRACE_LEVEL >= 2
  333. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  334. #endif
  335. continue;
  336. }
  337. auto exchangeNode = chainNodeOptional.get();
  338. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  339. {
  340. #if AI_TRACE_LEVEL >= 2
  341. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  342. #endif
  343. continue;
  344. }
  345. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  346. {
  347. #if AI_TRACE_LEVEL >= 2
  348. logAi->trace(
  349. "Exchange at %s is is not effective enough. %f < %f",
  350. exchangeNode->coord.toString(),
  351. exchangeNode->cost,
  352. chainInfo.cost);
  353. #endif
  354. continue;
  355. }
  356. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  357. if(carrier->specialAction || carrier->chainOther)
  358. {
  359. // there is some action on source tile which should be performed before we can bypass it
  360. exchangeNode->theNodeBefore = carrier;
  361. }
  362. exchangeNode->chainOther = other;
  363. exchangeNode->armyLoss = chainInfo.armyLoss;
  364. #if AI_TRACE_LEVEL >= 2
  365. logAi->trace(
  366. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  367. exchangeNode->coord.toString(),
  368. other->actor->toString(),
  369. exchangeNode->actor->toString(),
  370. exchangeNode->actor->chainMask,
  371. exchangeNode->cost,
  372. std::to_string(exchangeNode->turns),
  373. exchangeNode->moveRemains,
  374. exchangeNode->actor->armyValue);
  375. #endif
  376. heroChain.push_back(exchangeNode);
  377. }
  378. }
  379. ExchangeCandidate AINodeStorage::calculateExchange(
  380. ChainActor * exchangeActor,
  381. AIPathNode * carrierParentNode,
  382. AIPathNode * otherParentNode) const
  383. {
  384. ExchangeCandidate candidate;
  385. candidate.layer = carrierParentNode->layer;
  386. candidate.coord = carrierParentNode->coord;
  387. candidate.carrierParent = carrierParentNode;
  388. candidate.otherParent = otherParentNode;
  389. candidate.actor = exchangeActor;
  390. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  391. candidate.turns = carrierParentNode->turns;
  392. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  393. candidate.moveRemains = carrierParentNode->moveRemains;
  394. if(carrierParentNode->turns < otherParentNode->turns)
  395. {
  396. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  397. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  398. + carrierParentNode->moveRemains / (float)moveRemains;
  399. candidate.turns = otherParentNode->turns;
  400. candidate.cost += waitingCost;
  401. candidate.moveRemains = moveRemains;
  402. }
  403. return candidate;
  404. }
  405. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  406. {
  407. auto aiNode = getAINode(node);
  408. return aiNode->actor->hero;
  409. }
  410. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  411. {
  412. std::set<const CGHeroInstance *> heroes;
  413. for(auto actor : actors)
  414. {
  415. if(actor->hero)
  416. heroes.insert(actor->hero);
  417. }
  418. return heroes;
  419. }
  420. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  421. {
  422. cb = _ai->myCb.get();
  423. ai = _ai;
  424. playerID = ai->playerID;
  425. for(auto & hero : heroes)
  426. {
  427. uint64_t mask = 1 << actors.size();
  428. auto actor = std::make_shared<HeroActor>(hero.get(), mask, ai);
  429. if(hero->tempOwner != ai->playerID)
  430. {
  431. bool onLand = !actor->hero->boat;
  432. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  433. }
  434. playerID = hero->tempOwner;
  435. actors.push_back(actor);
  436. }
  437. }
  438. void AINodeStorage::setTownsAndDwellings(
  439. const std::vector<const CGTownInstance *> & towns,
  440. const std::set<const CGObjectInstance *> & visitableObjs)
  441. {
  442. for(auto town : towns)
  443. {
  444. uint64_t mask = 1 << actors.size();
  445. if(!town->garrisonHero && town->getUpperArmy()->getArmyStrength())
  446. {
  447. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  448. }
  449. }
  450. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  451. auto waitForGrowth = dayOfWeek > 4;
  452. for(auto obj: visitableObjs)
  453. {
  454. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  455. if(dwelling)
  456. {
  457. uint64_t mask = 1 << actors.size();
  458. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  459. if(dwellingActor->creatureSet->getArmyStrength())
  460. {
  461. actors.push_back(dwellingActor);
  462. }
  463. if(waitForGrowth)
  464. {
  465. mask = 1 << actors.size();
  466. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  467. if(dwellingActor->creatureSet->getArmyStrength())
  468. {
  469. actors.push_back(dwellingActor);
  470. }
  471. }
  472. }
  473. }*/
  474. }
  475. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  476. const PathNodeInfo & source,
  477. const PathfinderConfig * pathfinderConfig,
  478. const CPathfinderHelper * pathfinderHelper)
  479. {
  480. std::vector<CGPathNode *> neighbours;
  481. if(source.isNodeObjectVisitable())
  482. {
  483. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  484. auto srcNode = getAINode(source.node);
  485. for(auto & neighbour : accessibleExits)
  486. {
  487. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  488. if(!node)
  489. continue;
  490. neighbours.push_back(node.get());
  491. }
  492. }
  493. return neighbours;
  494. }
  495. struct TowmPortalFinder
  496. {
  497. const std::vector<CGPathNode *> & initialNodes;
  498. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  499. uint64_t movementNeeded;
  500. const ChainActor * actor;
  501. const CGHeroInstance * hero;
  502. std::vector<const CGTownInstance *> targetTowns;
  503. AINodeStorage * nodeStorage;
  504. SpellID spellID;
  505. const CSpell * townPortal;
  506. TowmPortalFinder(
  507. const ChainActor * actor,
  508. const std::vector<CGPathNode *> & initialNodes,
  509. std::vector<const CGTownInstance *> targetTowns,
  510. AINodeStorage * nodeStorage)
  511. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  512. targetTowns(targetTowns), nodeStorage(nodeStorage)
  513. {
  514. spellID = SpellID::TOWN_PORTAL;
  515. townPortal = spellID.toSpell();
  516. // TODO: Copy/Paste from TownPortalMechanics
  517. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  518. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  519. }
  520. bool actorCanCastTownPortal()
  521. {
  522. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  523. }
  524. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  525. {
  526. CGPathNode * bestNode = nullptr;
  527. for(CGPathNode * node : initialNodes)
  528. {
  529. auto aiNode = nodeStorage->getAINode(node);
  530. if(aiNode->actor->baseActor != actor
  531. || node->layer != EPathfindingLayer::LAND
  532. || node->moveRemains < movementNeeded)
  533. {
  534. continue;
  535. }
  536. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  537. {
  538. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  539. {
  540. return node->coord.dist2dSQ(t->visitablePos());
  541. });
  542. if(targetTown != nearestTown)
  543. continue;
  544. }
  545. if(!bestNode || bestNode->cost > node->cost)
  546. bestNode = node;
  547. }
  548. return bestNode;
  549. }
  550. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  551. {
  552. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  553. if(!bestNode)
  554. return boost::none;
  555. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  556. if(!nodeOptional)
  557. return boost::none;
  558. AIPathNode * node = nodeOptional.get();
  559. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  560. movementCost += bestNode->cost;
  561. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  562. {
  563. nodeStorage->commit(
  564. node,
  565. nodeStorage->getAINode(bestNode),
  566. CGPathNode::TELEPORT_NORMAL,
  567. bestNode->turns,
  568. bestNode->moveRemains - movementNeeded,
  569. movementCost);
  570. node->theNodeBefore = bestNode;
  571. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  572. }
  573. return nodeOptional;
  574. }
  575. };
  576. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  577. {
  578. std::set<const ChainActor *> actorsOfInitial;
  579. for(const CGPathNode * node : initialNodes)
  580. {
  581. auto aiNode = getAINode(node);
  582. actorsOfInitial.insert(aiNode->actor->baseActor);
  583. }
  584. for(const ChainActor * actor : actorsOfInitial)
  585. {
  586. if(!actor->hero)
  587. continue;
  588. auto towns = cb->getTownsInfo(false);
  589. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  590. {
  591. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  592. });
  593. if(!towns.size())
  594. {
  595. return; // no towns no need to run loop further
  596. }
  597. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  598. if(townPortalFinder.actorCanCastTownPortal())
  599. {
  600. for(const CGTownInstance * targetTown : towns)
  601. {
  602. // TODO: allow to hide visiting hero in garrison
  603. if(targetTown->visitingHero && targetTown->visitingHero != actor->hero)
  604. continue;
  605. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  606. if(nodeOptional)
  607. {
  608. #if AI_TRACE_LEVEL >= 1
  609. logAi->trace("Adding town portal node at %s", targetTown->name);
  610. #endif
  611. initialNodes.push_back(nodeOptional.get());
  612. }
  613. }
  614. }
  615. }
  616. }
  617. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  618. {
  619. auto pos = destination.coord;
  620. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  621. return hasBetterChain(source.node, getAINode(destination.node), chains);
  622. }
  623. template<class NodeRange>
  624. bool AINodeStorage::hasBetterChain(
  625. const CGPathNode * source,
  626. const AIPathNode * candidateNode,
  627. const NodeRange & chains) const
  628. {
  629. auto candidateActor = candidateNode->actor;
  630. for(const AIPathNode & node : chains)
  631. {
  632. auto sameNode = node.actor == candidateNode->actor;
  633. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  634. {
  635. continue;
  636. }
  637. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  638. {
  639. if(node.cost < candidateNode->cost)
  640. {
  641. #if AI_TRACE_LEVEL >= 2
  642. logAi->trace(
  643. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  644. source->coord.toString(),
  645. candidateNode->coord.toString(),
  646. candidateNode->actor->hero->name,
  647. candidateNode->actor->chainMask,
  648. candidateNode->actor->armyValue,
  649. node.moveRemains - candidateNode->moveRemains);
  650. #endif
  651. return true;
  652. }
  653. }
  654. if((candidateActor->chainMask & node.actor->chainMask) == 0)
  655. continue;
  656. auto nodeActor = node.actor;
  657. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  658. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  659. if(nodeArmyValue > candidateArmyValue
  660. && node.cost <= candidateNode->cost)
  661. {
  662. #if AI_TRACE_LEVEL >= 2
  663. logAi->trace(
  664. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  665. source->coord.toString(),
  666. candidateNode->coord.toString(),
  667. candidateNode->actor->hero->name,
  668. candidateNode->actor->chainMask,
  669. candidateNode->actor->armyValue,
  670. node.moveRemains - candidateNode->moveRemains);
  671. #endif
  672. return true;
  673. }
  674. /*if(nodeArmyValue == candidateArmyValue
  675. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  676. && node.cost <= candidateNode->cost)
  677. {
  678. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  679. && node.cost == candidateNode->cost
  680. && &node < candidateNode)
  681. {
  682. continue;
  683. }
  684. #if AI_TRACE_LEVEL >= 2
  685. logAi->trace(
  686. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  687. source->coord.toString(),
  688. candidateNode->coord.toString(),
  689. candidateNode->actor->hero->name,
  690. candidateNode->actor->chainMask,
  691. candidateNode->actor->armyValue,
  692. node.moveRemains - candidateNode->moveRemains);
  693. #endif
  694. return true;
  695. }*/
  696. }
  697. return false;
  698. }
  699. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  700. {
  701. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  702. for(const AIPathNode & node : chains)
  703. {
  704. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  705. && node.actor && node.actor->hero == hero.h)
  706. {
  707. return true;
  708. }
  709. }
  710. return false;
  711. }
  712. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  713. {
  714. std::vector<AIPath> paths;
  715. paths.reserve(NUM_CHAINS / 4);
  716. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  717. for(const AIPathNode & node : chains)
  718. {
  719. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  720. {
  721. continue;
  722. }
  723. AIPath path;
  724. path.targetHero = node.actor->hero;
  725. path.heroArmy = node.actor->creatureSet;
  726. path.armyLoss = node.armyLoss;
  727. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  728. path.chainMask = node.actor->chainMask;
  729. path.exchangeCount = node.actor->actorExchangeCount;
  730. fillChainInfo(&node, path, -1);
  731. paths.push_back(path);
  732. }
  733. return paths;
  734. }
  735. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  736. {
  737. while(node != nullptr)
  738. {
  739. if(!node->actor->hero)
  740. return;
  741. if(node->chainOther)
  742. fillChainInfo(node->chainOther, path, parentIndex);
  743. //if(node->actor->hero->visitablePos() != node->coord)
  744. {
  745. AIPathNodeInfo pathNode;
  746. pathNode.cost = node->cost;
  747. pathNode.targetHero = node->actor->hero;
  748. pathNode.chainMask = node->actor->chainMask;
  749. pathNode.specialAction = node->specialAction;
  750. pathNode.turns = node->turns;
  751. pathNode.danger = node->danger;
  752. pathNode.coord = node->coord;
  753. pathNode.parentIndex = parentIndex;
  754. parentIndex = path.nodes.size();
  755. path.nodes.push_back(pathNode);
  756. }
  757. path.specialAction = node->specialAction;
  758. node = getAINode(node->theNodeBefore);
  759. }
  760. }
  761. AIPath::AIPath()
  762. : nodes({})
  763. {
  764. }
  765. int3 AIPath::firstTileToGet() const
  766. {
  767. if(nodes.size())
  768. {
  769. return nodes.back().coord;
  770. }
  771. return int3(-1, -1, -1);
  772. }
  773. int3 AIPath::targetTile() const
  774. {
  775. if(nodes.size())
  776. {
  777. return targetNode().coord;
  778. }
  779. return int3(-1, -1, -1);
  780. }
  781. const AIPathNodeInfo & AIPath::firstNode() const
  782. {
  783. return nodes.back();
  784. }
  785. const AIPathNodeInfo & AIPath::targetNode() const
  786. {
  787. auto & node = nodes.front();
  788. return targetHero == node.targetHero ? node : nodes.at(1);
  789. }
  790. uint64_t AIPath::getPathDanger() const
  791. {
  792. if(nodes.empty())
  793. return 0;
  794. return targetNode().danger;
  795. }
  796. float AIPath::movementCost() const
  797. {
  798. if(nodes.empty())
  799. return 0.0f;
  800. return targetNode().cost;
  801. }
  802. uint8_t AIPath::turn() const
  803. {
  804. if(nodes.empty())
  805. return 0;
  806. return targetNode().turns;
  807. }
  808. uint64_t AIPath::getHeroStrength() const
  809. {
  810. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  811. }
  812. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  813. {
  814. uint64_t pathDanger = getPathDanger();
  815. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  816. return danger;
  817. }
  818. std::string AIPath::toString()
  819. {
  820. std::stringstream str;
  821. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ": ";
  822. for(auto node : nodes)
  823. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  824. return str.str();
  825. }