AINodeStorage.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. || node->action == CGPathNode::ENodeAction::TELEPORT_NORMAL
  345. || node->action == CGPathNode::ENodeAction::TELEPORT_BLOCKING_VISIT)
  346. {
  347. continue;
  348. }
  349. if(node->turns > heroChainTurn
  350. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  351. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  352. {
  353. #if AI_TRACE_LEVEL >= 2
  354. logAi->trace(
  355. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  356. node->actor->toString(),
  357. node->actor->chainMask,
  358. srcNode->actor->toString(),
  359. srcNode->actor->chainMask,
  360. srcNode->coord.toString(),
  361. (node->turns > heroChainTurn
  362. ? "turn limit"
  363. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  364. ? "action unknown"
  365. : "chain mask"));
  366. #endif
  367. continue;
  368. }
  369. #if AI_TRACE_LEVEL >= 2
  370. logAi->trace(
  371. "Thy exchange %s[%x] -> %s[%x] at %s",
  372. node->actor->toString(),
  373. node->actor->chainMask,
  374. srcNode->actor->toString(),
  375. srcNode->actor->chainMask,
  376. srcNode->coord.toString());
  377. #endif
  378. calculateHeroChain(srcNode, node, result);
  379. }
  380. }
  381. void AINodeStorage::calculateHeroChain(
  382. AIPathNode * carrier,
  383. AIPathNode * other,
  384. std::vector<ExchangeCandidate> & result) const
  385. {
  386. if(carrier->armyLoss < carrier->actor->armyValue
  387. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  388. && carrier->action != CGPathNode::BLOCKING_VISIT
  389. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue)
  390. && carrier->actor->canExchange(other->actor))
  391. {
  392. #if AI_TRACE_LEVEL >= 2
  393. logAi->trace(
  394. "Exchange allowed %s[%x] -> %s[%x] at %s",
  395. other->actor->toString(),
  396. other->actor->chainMask,
  397. carrier->actor->toString(),
  398. carrier->actor->chainMask,
  399. carrier->coord.toString());
  400. #endif
  401. if(other->actor->isMovable)
  402. {
  403. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  404. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  405. if(hasLessMp && hasLessExperience)
  406. {
  407. #if AI_TRACE_LEVEL >= 2
  408. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  409. #endif
  410. return;
  411. }
  412. }
  413. auto newActor = carrier->actor->exchange(other->actor);
  414. result.push_back(calculateExchange(newActor, carrier, other));
  415. }
  416. }
  417. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  418. {
  419. for(const ExchangeCandidate & chainInfo : result)
  420. {
  421. auto carrier = chainInfo.carrierParent;
  422. auto newActor = chainInfo.actor;
  423. auto other = chainInfo.otherParent;
  424. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  425. if(!chainNodeOptional)
  426. {
  427. #if AI_TRACE_LEVEL >= 2
  428. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  429. #endif
  430. continue;
  431. }
  432. auto exchangeNode = chainNodeOptional.get();
  433. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  434. {
  435. #if AI_TRACE_LEVEL >= 2
  436. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  437. #endif
  438. continue;
  439. }
  440. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  441. {
  442. #if AI_TRACE_LEVEL >= 2
  443. logAi->trace(
  444. "Exchange at %s is is not effective enough. %f < %f",
  445. exchangeNode->coord.toString(),
  446. exchangeNode->cost,
  447. chainInfo.cost);
  448. #endif
  449. continue;
  450. }
  451. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  452. if(carrier->specialAction || carrier->chainOther)
  453. {
  454. // there is some action on source tile which should be performed before we can bypass it
  455. exchangeNode->theNodeBefore = carrier;
  456. }
  457. exchangeNode->chainOther = other;
  458. exchangeNode->armyLoss = chainInfo.armyLoss;
  459. #if AI_TRACE_LEVEL >= 2
  460. logAi->trace(
  461. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  462. exchangeNode->coord.toString(),
  463. other->actor->toString(),
  464. exchangeNode->actor->toString(),
  465. exchangeNode->actor->chainMask,
  466. exchangeNode->cost,
  467. std::to_string(exchangeNode->turns),
  468. exchangeNode->moveRemains,
  469. exchangeNode->actor->armyValue);
  470. #endif
  471. heroChain.push_back(exchangeNode);
  472. }
  473. }
  474. ExchangeCandidate AINodeStorage::calculateExchange(
  475. ChainActor * exchangeActor,
  476. AIPathNode * carrierParentNode,
  477. AIPathNode * otherParentNode) const
  478. {
  479. ExchangeCandidate candidate;
  480. candidate.layer = carrierParentNode->layer;
  481. candidate.coord = carrierParentNode->coord;
  482. candidate.carrierParent = carrierParentNode;
  483. candidate.otherParent = otherParentNode;
  484. candidate.actor = exchangeActor;
  485. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  486. candidate.turns = carrierParentNode->turns;
  487. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  488. candidate.moveRemains = carrierParentNode->moveRemains;
  489. if(carrierParentNode->turns < otherParentNode->turns)
  490. {
  491. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  492. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  493. + carrierParentNode->moveRemains / (float)moveRemains;
  494. candidate.turns = otherParentNode->turns;
  495. candidate.cost += waitingCost;
  496. candidate.moveRemains = moveRemains;
  497. }
  498. return candidate;
  499. }
  500. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  501. {
  502. auto aiNode = getAINode(node);
  503. return aiNode->actor->hero;
  504. }
  505. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  506. {
  507. std::set<const CGHeroInstance *> heroes;
  508. for(auto actor : actors)
  509. {
  510. if(actor->hero)
  511. heroes.insert(actor->hero);
  512. }
  513. return heroes;
  514. }
  515. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  516. {
  517. cb = _ai->myCb.get();
  518. ai = _ai;
  519. playerID = ai->playerID;
  520. for(auto & hero : heroes)
  521. {
  522. uint64_t mask = 1 << actors.size();
  523. auto actor = std::make_shared<HeroActor>(hero.get(), mask, ai);
  524. if(hero->tempOwner != ai->playerID)
  525. {
  526. bool onLand = !actor->hero->boat;
  527. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  528. }
  529. playerID = hero->tempOwner;
  530. actors.push_back(actor);
  531. }
  532. }
  533. void AINodeStorage::setTownsAndDwellings(
  534. const std::vector<const CGTownInstance *> & towns,
  535. const std::set<const CGObjectInstance *> & visitableObjs)
  536. {
  537. for(auto town : towns)
  538. {
  539. uint64_t mask = 1 << actors.size();
  540. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
  541. // check defence imrove
  542. if(!town->garrisonHero)
  543. {
  544. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  545. }
  546. }
  547. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  548. auto waitForGrowth = dayOfWeek > 4;*/
  549. for(auto obj: visitableObjs)
  550. {
  551. if(obj->ID == Obj::HILL_FORT)
  552. {
  553. uint64_t mask = 1 << actors.size();
  554. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  555. }
  556. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  557. if(dwelling)
  558. {
  559. uint64_t mask = 1 << actors.size();
  560. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  561. if(dwellingActor->creatureSet->getArmyStrength())
  562. {
  563. actors.push_back(dwellingActor);
  564. }
  565. if(waitForGrowth)
  566. {
  567. mask = 1 << actors.size();
  568. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  569. if(dwellingActor->creatureSet->getArmyStrength())
  570. {
  571. actors.push_back(dwellingActor);
  572. }
  573. }
  574. }*/
  575. }
  576. }
  577. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  578. const PathNodeInfo & source,
  579. const PathfinderConfig * pathfinderConfig,
  580. const CPathfinderHelper * pathfinderHelper)
  581. {
  582. std::vector<CGPathNode *> neighbours;
  583. if(source.isNodeObjectVisitable())
  584. {
  585. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  586. auto srcNode = getAINode(source.node);
  587. for(auto & neighbour : accessibleExits)
  588. {
  589. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  590. if(!node)
  591. continue;
  592. neighbours.push_back(node.get());
  593. }
  594. }
  595. return neighbours;
  596. }
  597. struct TowmPortalFinder
  598. {
  599. const std::vector<CGPathNode *> & initialNodes;
  600. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  601. uint64_t movementNeeded;
  602. const ChainActor * actor;
  603. const CGHeroInstance * hero;
  604. std::vector<const CGTownInstance *> targetTowns;
  605. AINodeStorage * nodeStorage;
  606. SpellID spellID;
  607. const CSpell * townPortal;
  608. TowmPortalFinder(
  609. const ChainActor * actor,
  610. const std::vector<CGPathNode *> & initialNodes,
  611. std::vector<const CGTownInstance *> targetTowns,
  612. AINodeStorage * nodeStorage)
  613. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  614. targetTowns(targetTowns), nodeStorage(nodeStorage)
  615. {
  616. spellID = SpellID::TOWN_PORTAL;
  617. townPortal = spellID.toSpell();
  618. // TODO: Copy/Paste from TownPortalMechanics
  619. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  620. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  621. }
  622. bool actorCanCastTownPortal()
  623. {
  624. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  625. }
  626. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  627. {
  628. CGPathNode * bestNode = nullptr;
  629. for(CGPathNode * node : initialNodes)
  630. {
  631. auto aiNode = nodeStorage->getAINode(node);
  632. if(aiNode->actor->baseActor != actor
  633. || node->layer != EPathfindingLayer::LAND
  634. || node->moveRemains < movementNeeded)
  635. {
  636. continue;
  637. }
  638. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  639. {
  640. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  641. {
  642. return node->coord.dist2dSQ(t->visitablePos());
  643. });
  644. if(targetTown != nearestTown)
  645. continue;
  646. }
  647. if(!bestNode || bestNode->cost > node->cost)
  648. bestNode = node;
  649. }
  650. return bestNode;
  651. }
  652. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  653. {
  654. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  655. if(!bestNode)
  656. return boost::none;
  657. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  658. if(!nodeOptional)
  659. return boost::none;
  660. AIPathNode * node = nodeOptional.get();
  661. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  662. movementCost += bestNode->cost;
  663. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  664. {
  665. nodeStorage->commit(
  666. node,
  667. nodeStorage->getAINode(bestNode),
  668. CGPathNode::TELEPORT_NORMAL,
  669. bestNode->turns,
  670. bestNode->moveRemains - movementNeeded,
  671. movementCost);
  672. node->theNodeBefore = bestNode;
  673. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  674. }
  675. return nodeOptional;
  676. }
  677. };
  678. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  679. {
  680. std::set<const ChainActor *> actorsOfInitial;
  681. for(const CGPathNode * node : initialNodes)
  682. {
  683. auto aiNode = getAINode(node);
  684. actorsOfInitial.insert(aiNode->actor->baseActor);
  685. }
  686. for(const ChainActor * actor : actorsOfInitial)
  687. {
  688. if(!actor->hero)
  689. continue;
  690. auto towns = cb->getTownsInfo(false);
  691. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  692. {
  693. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  694. });
  695. if(!towns.size())
  696. {
  697. return; // no towns no need to run loop further
  698. }
  699. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  700. if(townPortalFinder.actorCanCastTownPortal())
  701. {
  702. for(const CGTownInstance * targetTown : towns)
  703. {
  704. // TODO: allow to hide visiting hero in garrison
  705. if(targetTown->visitingHero && targetTown->visitingHero != actor->hero)
  706. continue;
  707. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  708. if(nodeOptional)
  709. {
  710. #if AI_TRACE_LEVEL >= 1
  711. logAi->trace("Adding town portal node at %s", targetTown->name);
  712. #endif
  713. initialNodes.push_back(nodeOptional.get());
  714. }
  715. }
  716. }
  717. }
  718. }
  719. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  720. {
  721. auto pos = destination.coord;
  722. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  723. return hasBetterChain(source.node, getAINode(destination.node), chains);
  724. }
  725. template<class NodeRange>
  726. bool AINodeStorage::hasBetterChain(
  727. const CGPathNode * source,
  728. const AIPathNode * candidateNode,
  729. const NodeRange & chains) const
  730. {
  731. auto candidateActor = candidateNode->actor;
  732. for(const AIPathNode & node : chains)
  733. {
  734. auto sameNode = node.actor == candidateNode->actor;
  735. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  736. {
  737. continue;
  738. }
  739. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  740. {
  741. if(node.cost < candidateNode->cost)
  742. {
  743. #if AI_TRACE_LEVEL >= 2
  744. logAi->trace(
  745. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  746. source->coord.toString(),
  747. candidateNode->coord.toString(),
  748. candidateNode->actor->hero->name,
  749. candidateNode->actor->chainMask,
  750. candidateNode->actor->armyValue,
  751. node.moveRemains - candidateNode->moveRemains);
  752. #endif
  753. return true;
  754. }
  755. }
  756. if(candidateActor->chainMask != node.actor->chainMask)
  757. continue;
  758. auto nodeActor = node.actor;
  759. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  760. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  761. if(nodeArmyValue > candidateArmyValue
  762. && node.cost <= candidateNode->cost)
  763. {
  764. #if AI_TRACE_LEVEL >= 2
  765. logAi->trace(
  766. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  767. source->coord.toString(),
  768. candidateNode->coord.toString(),
  769. candidateNode->actor->hero->name,
  770. candidateNode->actor->chainMask,
  771. candidateNode->actor->armyValue,
  772. node.moveRemains - candidateNode->moveRemains);
  773. #endif
  774. return true;
  775. }
  776. /*if(nodeArmyValue == candidateArmyValue
  777. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  778. && node.cost <= candidateNode->cost)
  779. {
  780. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  781. && node.cost == candidateNode->cost
  782. && &node < candidateNode)
  783. {
  784. continue;
  785. }
  786. #if AI_TRACE_LEVEL >= 2
  787. logAi->trace(
  788. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  789. source->coord.toString(),
  790. candidateNode->coord.toString(),
  791. candidateNode->actor->hero->name,
  792. candidateNode->actor->chainMask,
  793. candidateNode->actor->armyValue,
  794. node.moveRemains - candidateNode->moveRemains);
  795. #endif
  796. return true;
  797. }*/
  798. }
  799. return false;
  800. }
  801. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  802. {
  803. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  804. for(const AIPathNode & node : chains)
  805. {
  806. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  807. && node.actor && node.actor->hero == hero.h)
  808. {
  809. return true;
  810. }
  811. }
  812. return false;
  813. }
  814. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  815. {
  816. std::vector<AIPath> paths;
  817. paths.reserve(NUM_CHAINS / 4);
  818. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  819. for(const AIPathNode & node : chains)
  820. {
  821. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  822. {
  823. continue;
  824. }
  825. AIPath path;
  826. path.targetHero = node.actor->hero;
  827. path.heroArmy = node.actor->creatureSet;
  828. path.armyLoss = node.armyLoss;
  829. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, false);
  830. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  831. path.chainMask = node.actor->chainMask;
  832. path.exchangeCount = node.actor->actorExchangeCount;
  833. fillChainInfo(&node, path, -1);
  834. paths.push_back(path);
  835. }
  836. return paths;
  837. }
  838. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  839. {
  840. while(node != nullptr)
  841. {
  842. if(!node->actor->hero)
  843. return;
  844. if(node->chainOther)
  845. fillChainInfo(node->chainOther, path, parentIndex);
  846. //if(node->actor->hero->visitablePos() != node->coord)
  847. {
  848. AIPathNodeInfo pathNode;
  849. pathNode.cost = node->cost;
  850. pathNode.targetHero = node->actor->hero;
  851. pathNode.chainMask = node->actor->chainMask;
  852. pathNode.specialAction = node->specialAction;
  853. pathNode.turns = node->turns;
  854. pathNode.danger = node->danger;
  855. pathNode.coord = node->coord;
  856. pathNode.parentIndex = parentIndex;
  857. parentIndex = path.nodes.size();
  858. path.nodes.push_back(pathNode);
  859. }
  860. path.specialAction = node->specialAction;
  861. node = getAINode(node->theNodeBefore);
  862. }
  863. }
  864. AIPath::AIPath()
  865. : nodes({})
  866. {
  867. }
  868. std::shared_ptr<const ISpecialAction> AIPath::getFirstBlockedAction() const
  869. {
  870. for(auto node : nodes)
  871. {
  872. if(node.specialAction && !node.specialAction->canAct(node.targetHero))
  873. return node.specialAction;
  874. }
  875. return std::shared_ptr<const ISpecialAction>();
  876. }
  877. int3 AIPath::firstTileToGet() const
  878. {
  879. if(nodes.size())
  880. {
  881. return nodes.back().coord;
  882. }
  883. return int3(-1, -1, -1);
  884. }
  885. int3 AIPath::targetTile() const
  886. {
  887. if(nodes.size())
  888. {
  889. return targetNode().coord;
  890. }
  891. return int3(-1, -1, -1);
  892. }
  893. const AIPathNodeInfo & AIPath::firstNode() const
  894. {
  895. return nodes.back();
  896. }
  897. const AIPathNodeInfo & AIPath::targetNode() const
  898. {
  899. auto & node = nodes.front();
  900. return targetHero == node.targetHero ? node : nodes.at(1);
  901. }
  902. uint64_t AIPath::getPathDanger() const
  903. {
  904. if(nodes.empty())
  905. return 0;
  906. return targetNode().danger;
  907. }
  908. float AIPath::movementCost() const
  909. {
  910. if(nodes.empty())
  911. return 0.0f;
  912. return targetNode().cost;
  913. }
  914. uint8_t AIPath::turn() const
  915. {
  916. if(nodes.empty())
  917. return 0;
  918. return targetNode().turns;
  919. }
  920. uint64_t AIPath::getHeroStrength() const
  921. {
  922. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  923. }
  924. uint64_t AIPath::getTotalDanger() const
  925. {
  926. uint64_t pathDanger = getPathDanger();
  927. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  928. return danger;
  929. }
  930. bool AIPath::containsHero(const CGHeroInstance * hero) const
  931. {
  932. if(targetHero == hero)
  933. return true;
  934. for(auto node : nodes)
  935. {
  936. if(node.targetHero == hero)
  937. return true;
  938. }
  939. return false;
  940. }
  941. uint64_t AIPath::getTotalArmyLoss() const
  942. {
  943. return armyLoss + targetObjectArmyLoss;
  944. }
  945. std::string AIPath::toString() const
  946. {
  947. std::stringstream str;
  948. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ": ";
  949. for(auto node : nodes)
  950. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  951. return str.str();
  952. }