AINodeStorage.cpp 25 KB

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