AINodeStorage.cpp 29 KB

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