AINodeStorage.cpp 28 KB

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