AIPathfinderConfig.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. * AIPathfinderConfig.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 "AIPathfinderConfig.h"
  12. #include "../Goals/Goals.h"
  13. #include "../../../CCallback.h"
  14. #include "../../../lib/mapping/CMap.h"
  15. #include "../../../lib/mapObjects/MapObjects.h"
  16. namespace AIPathfinding
  17. {
  18. class VirtualBoatAction : public ISpecialAction
  19. {
  20. private:
  21. uint64_t specialChain;
  22. public:
  23. VirtualBoatAction(uint64_t specialChain)
  24. :specialChain(specialChain)
  25. {
  26. }
  27. uint64_t getSpecialChain() const
  28. {
  29. return specialChain;
  30. }
  31. };
  32. class BuildBoatAction : public VirtualBoatAction
  33. {
  34. private:
  35. const IShipyard * shipyard;
  36. public:
  37. BuildBoatAction(const IShipyard * shipyard)
  38. :VirtualBoatAction(AINodeStorage::RESOURCE_CHAIN), shipyard(shipyard)
  39. {
  40. }
  41. virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
  42. {
  43. return sptr(Goals::BuildBoat(shipyard));
  44. }
  45. };
  46. class SummonBoatAction : public VirtualBoatAction
  47. {
  48. public:
  49. SummonBoatAction()
  50. :VirtualBoatAction(AINodeStorage::CAST_CHAIN)
  51. {
  52. }
  53. virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
  54. {
  55. return sptr(Goals::AdventureSpellCast(hero, SpellID::SUMMON_BOAT));
  56. }
  57. virtual void applyOnDestination(
  58. HeroPtr hero,
  59. CDestinationNodeInfo & destination,
  60. const PathNodeInfo & source,
  61. AIPathNode * dstMode,
  62. const AIPathNode * srcNode) const override
  63. {
  64. dstMode->manaCost = srcNode->manaCost + getManaCost(hero);
  65. dstMode->theNodeBefore = source.node;
  66. }
  67. bool isAffordableBy(HeroPtr hero, const AIPathNode * source) const
  68. {
  69. logAi->trace(
  70. "Hero %s has %d mana and needed %d and already spent %d",
  71. hero->name,
  72. hero->mana,
  73. getManaCost(hero),
  74. source->manaCost);
  75. return hero->mana >= source->manaCost + getManaCost(hero);
  76. }
  77. private:
  78. uint32_t getManaCost(HeroPtr hero) const
  79. {
  80. SpellID summonBoat = SpellID::SUMMON_BOAT;
  81. return hero->getSpellCost(summonBoat.toSpell());
  82. }
  83. };
  84. class BattleAction : public ISpecialAction
  85. {
  86. private:
  87. const int3 target;
  88. const HeroPtr hero;
  89. public:
  90. BattleAction(const int3 target)
  91. :target(target)
  92. {
  93. }
  94. virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
  95. {
  96. return sptr(Goals::VisitTile(target).sethero(hero));
  97. }
  98. };
  99. class AILayerTransitionRule : public LayerTransitionRule
  100. {
  101. private:
  102. CPlayerSpecificInfoCallback * cb;
  103. VCAI * ai;
  104. std::map<int3, std::shared_ptr<const BuildBoatAction>> virtualBoats;
  105. std::shared_ptr<AINodeStorage> nodeStorage;
  106. std::shared_ptr<const SummonBoatAction> summonableVirtualBoat;
  107. public:
  108. AILayerTransitionRule(CPlayerSpecificInfoCallback * cb, VCAI * ai, std::shared_ptr<AINodeStorage> nodeStorage)
  109. :cb(cb), ai(ai), nodeStorage(nodeStorage)
  110. {
  111. setup();
  112. }
  113. virtual void process(
  114. const PathNodeInfo & source,
  115. CDestinationNodeInfo & destination,
  116. const PathfinderConfig * pathfinderConfig,
  117. CPathfinderHelper * pathfinderHelper) const override
  118. {
  119. LayerTransitionRule::process(source, destination, pathfinderConfig, pathfinderHelper);
  120. if(!destination.blocked)
  121. {
  122. return;
  123. }
  124. if(source.node->layer == EPathfindingLayer::LAND && destination.node->layer == EPathfindingLayer::SAIL)
  125. {
  126. std::shared_ptr<const VirtualBoatAction> virtualBoat = findVirtualBoat(destination, source);
  127. if(virtualBoat && tryEmbarkVirtualBoat(destination, source, virtualBoat))
  128. {
  129. logAi->trace("Embarking to virtual boat while moving %s -> %s!", source.coord.toString(), destination.coord.toString());
  130. }
  131. }
  132. }
  133. private:
  134. void setup()
  135. {
  136. std::vector<const IShipyard *> shipyards;
  137. for(const CGTownInstance * t : cb->getTownsInfo())
  138. {
  139. if(t->hasBuilt(BuildingID::SHIPYARD))
  140. shipyards.push_back(t);
  141. }
  142. for(const CGObjectInstance * obj : ai->visitableObjs)
  143. {
  144. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  145. {
  146. if(const IShipyard * shipyard = IShipyard::castFrom(obj))
  147. shipyards.push_back(shipyard);
  148. }
  149. }
  150. for(const IShipyard * shipyard : shipyards)
  151. {
  152. if(shipyard->shipyardStatus() == IShipyard::GOOD)
  153. {
  154. int3 boatLocation = shipyard->bestLocation();
  155. virtualBoats[boatLocation] = std::make_shared<BuildBoatAction>(shipyard);
  156. logAi->debug("Virtual boat added at %s", boatLocation.toString());
  157. }
  158. }
  159. auto hero = nodeStorage->getHero();
  160. auto summonBoatSpell = SpellID(SpellID::SUMMON_BOAT).toSpell();
  161. if(hero->canCastThisSpell(summonBoatSpell)
  162. && hero->getSpellSchoolLevel(summonBoatSpell) >= SecSkillLevel::ADVANCED)
  163. {
  164. // TODO: For lower school level we might need to check the existance of some boat
  165. summonableVirtualBoat.reset(new SummonBoatAction());
  166. }
  167. }
  168. std::shared_ptr<const VirtualBoatAction> findVirtualBoat(
  169. CDestinationNodeInfo &destination,
  170. const PathNodeInfo &source) const
  171. {
  172. std::shared_ptr<const VirtualBoatAction> virtualBoat;
  173. if(vstd::contains(virtualBoats, destination.coord))
  174. {
  175. virtualBoat = virtualBoats.at(destination.coord);
  176. }
  177. else if(
  178. summonableVirtualBoat
  179. && summonableVirtualBoat->isAffordableBy(nodeStorage->getHero(), nodeStorage->getAINode(source.node)))
  180. {
  181. virtualBoat = summonableVirtualBoat;
  182. }
  183. return virtualBoat;
  184. }
  185. bool tryEmbarkVirtualBoat(
  186. CDestinationNodeInfo &destination,
  187. const PathNodeInfo &source,
  188. std::shared_ptr<const VirtualBoatAction> virtualBoat) const
  189. {
  190. bool result = false;
  191. nodeStorage->updateAINode(destination.node, [&](AIPathNode * node)
  192. {
  193. auto boatNodeOptional = nodeStorage->getOrCreateNode(
  194. node->coord,
  195. node->layer,
  196. node->chainMask | virtualBoat->getSpecialChain());
  197. if(boatNodeOptional)
  198. {
  199. AIPathNode * boatNode = boatNodeOptional.get();
  200. if(boatNode->action == CGPathNode::NOT_SET)
  201. {
  202. boatNode->specialAction = virtualBoat;
  203. destination.blocked = false;
  204. destination.action = CGPathNode::ENodeAction::EMBARK;
  205. destination.node = boatNode;
  206. result = true;
  207. }
  208. else
  209. {
  210. logAi->trace(
  211. "Special transition node already allocated. Blocked moving %s -> %s",
  212. source.coord.toString(),
  213. destination.coord.toString());
  214. }
  215. }
  216. else
  217. {
  218. logAi->trace(
  219. "Can not allocate special transition node while moving %s -> %s",
  220. source.coord.toString(),
  221. destination.coord.toString());
  222. }
  223. });
  224. return result;
  225. }
  226. };
  227. class AIMovementAfterDestinationRule : public MovementAfterDestinationRule
  228. {
  229. private:
  230. CPlayerSpecificInfoCallback * cb;
  231. std::shared_ptr<AINodeStorage> nodeStorage;
  232. public:
  233. AIMovementAfterDestinationRule(CPlayerSpecificInfoCallback * cb, std::shared_ptr<AINodeStorage> nodeStorage)
  234. :cb(cb), nodeStorage(nodeStorage)
  235. {
  236. }
  237. virtual void process(
  238. const PathNodeInfo & source,
  239. CDestinationNodeInfo & destination,
  240. const PathfinderConfig * pathfinderConfig,
  241. CPathfinderHelper * pathfinderHelper) const override
  242. {
  243. if(nodeStorage->hasBetterChain(source, destination))
  244. {
  245. destination.blocked = true;
  246. return;
  247. }
  248. auto blocker = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);
  249. if(blocker == BlockingReason::NONE)
  250. return;
  251. if(blocker == BlockingReason::DESTINATION_BLOCKVIS && destination.nodeObject)
  252. {
  253. auto objID = destination.nodeObject->ID;
  254. if((objID == Obj::HERO && destination.objectRelations != PlayerRelations::ENEMIES)
  255. || objID == Obj::SUBTERRANEAN_GATE || objID == Obj::MONOLITH_TWO_WAY
  256. || objID == Obj::MONOLITH_ONE_WAY_ENTRANCE || objID == Obj::MONOLITH_ONE_WAY_EXIT
  257. || objID == Obj::WHIRLPOOL)
  258. {
  259. destination.blocked = true;
  260. }
  261. return;
  262. }
  263. if(blocker == BlockingReason::DESTINATION_VISIT)
  264. {
  265. return;
  266. }
  267. if(blocker == BlockingReason::DESTINATION_GUARDED)
  268. {
  269. auto srcGuardians = cb->getGuardingCreatures(source.coord);
  270. auto destGuardians = cb->getGuardingCreatures(destination.coord);
  271. if(destGuardians.empty())
  272. {
  273. destination.blocked = true;
  274. return;
  275. }
  276. vstd::erase_if(destGuardians, [&](const CGObjectInstance * destGuard) -> bool
  277. {
  278. return vstd::contains(srcGuardians, destGuard);
  279. });
  280. auto guardsAlreadyBypassed = destGuardians.empty() && srcGuardians.size();
  281. if(guardsAlreadyBypassed && nodeStorage->isBattleNode(source.node))
  282. {
  283. //logAi->trace(
  284. // "Bypass guard at destination while moving %s -> %s",
  285. // source.coord.toString(),
  286. // destination.coord.toString());
  287. return;
  288. }
  289. const AIPathNode * destNode = nodeStorage->getAINode(destination.node);
  290. auto battleNodeOptional = nodeStorage->getOrCreateNode(
  291. destination.coord,
  292. destination.node->layer,
  293. destNode->chainMask | AINodeStorage::BATTLE_CHAIN);
  294. if(!battleNodeOptional)
  295. {
  296. //logAi->trace(
  297. // "Can not allocate battle node while moving %s -> %s",
  298. // source.coord.toString(),
  299. // destination.coord.toString());
  300. destination.blocked = true;
  301. return;
  302. }
  303. AIPathNode * battleNode = battleNodeOptional.get();
  304. if(battleNode->locked)
  305. {
  306. //logAi->trace(
  307. // "Block bypass guard at destination while moving %s -> %s",
  308. // source.coord.toString(),
  309. // destination.coord.toString());
  310. destination.blocked = true;
  311. return;
  312. }
  313. auto hero = nodeStorage->getHero();
  314. auto danger = evaluateDanger(destination.coord, hero);
  315. destination.node = battleNode;
  316. nodeStorage->commit(destination, source);
  317. if(battleNode->danger < danger)
  318. {
  319. battleNode->danger = danger;
  320. }
  321. battleNode->specialAction = std::make_shared<BattleAction>(destination.coord);
  322. //logAi->trace(
  323. // "Begin bypass guard at destination with danger %s while moving %s -> %s",
  324. // std::to_string(danger),
  325. // source.coord.toString(),
  326. // destination.coord.toString());
  327. return;
  328. }
  329. destination.blocked = true;
  330. }
  331. };
  332. class AIMovementToDestinationRule : public MovementToDestinationRule
  333. {
  334. private:
  335. CPlayerSpecificInfoCallback * cb;
  336. std::shared_ptr<AINodeStorage> nodeStorage;
  337. public:
  338. AIMovementToDestinationRule(CPlayerSpecificInfoCallback * cb, std::shared_ptr<AINodeStorage> nodeStorage)
  339. :cb(cb), nodeStorage(nodeStorage)
  340. {
  341. }
  342. virtual void process(
  343. const PathNodeInfo & source,
  344. CDestinationNodeInfo & destination,
  345. const PathfinderConfig * pathfinderConfig,
  346. CPathfinderHelper * pathfinderHelper) const override
  347. {
  348. auto blocker = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);
  349. if(blocker == BlockingReason::NONE)
  350. return;
  351. if(blocker == BlockingReason::DESTINATION_BLOCKED
  352. && destination.action == CGPathNode::EMBARK
  353. && nodeStorage->getAINode(destination.node)->specialAction)
  354. {
  355. return;
  356. }
  357. if(blocker == BlockingReason::SOURCE_GUARDED && nodeStorage->isBattleNode(source.node))
  358. {
  359. //logAi->trace(
  360. // "Bypass src guard while moving from %s to %s",
  361. // source.coord.toString(),
  362. // destination.coord.toString());
  363. return;
  364. }
  365. destination.blocked = true;
  366. }
  367. };
  368. class AIPreviousNodeRule : public MovementToDestinationRule
  369. {
  370. private:
  371. CPlayerSpecificInfoCallback * cb;
  372. std::shared_ptr<AINodeStorage> nodeStorage;
  373. public:
  374. AIPreviousNodeRule(CPlayerSpecificInfoCallback * cb, std::shared_ptr<AINodeStorage> nodeStorage)
  375. :cb(cb), nodeStorage(nodeStorage)
  376. {
  377. }
  378. virtual void process(
  379. const PathNodeInfo & source,
  380. CDestinationNodeInfo & destination,
  381. const PathfinderConfig * pathfinderConfig,
  382. CPathfinderHelper * pathfinderHelper) const override
  383. {
  384. if(source.node->action == CGPathNode::ENodeAction::BLOCKING_VISIT || source.node->action == CGPathNode::ENodeAction::VISIT)
  385. {
  386. // we can not directly bypass objects, we need to interact with them first
  387. destination.node->theNodeBefore = source.node;
  388. //logAi->trace(
  389. // "Link src node %s to destination node %s while bypassing visitable obj",
  390. // source.coord.toString(),
  391. // destination.coord.toString());
  392. return;
  393. }
  394. auto aiSourceNode = nodeStorage->getAINode(source.node);
  395. if(aiSourceNode->specialAction)
  396. {
  397. // there is some action on source tile which should be performed before we can bypass it
  398. destination.node->theNodeBefore = source.node;
  399. }
  400. }
  401. };
  402. std::vector<std::shared_ptr<IPathfindingRule>> makeRuleset(
  403. CPlayerSpecificInfoCallback * cb,
  404. VCAI * ai,
  405. std::shared_ptr<AINodeStorage> nodeStorage)
  406. {
  407. std::vector<std::shared_ptr<IPathfindingRule>> rules = {
  408. std::make_shared<AILayerTransitionRule>(cb, ai, nodeStorage),
  409. std::make_shared<DestinationActionRule>(),
  410. std::make_shared<AIMovementToDestinationRule>(cb, nodeStorage),
  411. std::make_shared<MovementCostRule>(),
  412. std::make_shared<AIPreviousNodeRule>(cb, nodeStorage),
  413. std::make_shared<AIMovementAfterDestinationRule>(cb, nodeStorage)
  414. };
  415. return rules;
  416. }
  417. AIPathfinderConfig::AIPathfinderConfig(
  418. CPlayerSpecificInfoCallback * cb,
  419. VCAI * ai,
  420. std::shared_ptr<AINodeStorage> nodeStorage)
  421. :PathfinderConfig(nodeStorage, makeRuleset(cb, ai, nodeStorage))
  422. {
  423. }
  424. }