ObjectGraph.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. /*
  2. * ObjectGraph.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 "ObjectGraph.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../lib/CRandomGenerator.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../Engine/Nullkiller.h"
  17. #include "../../../lib/logging/VisualLogger.h"
  18. #include "Actions/QuestAction.h"
  19. namespace NKAI
  20. {
  21. struct ConnectionCostInfo
  22. {
  23. float totalCost = 0;
  24. float avg = 0;
  25. int connectionsCount = 0;
  26. };
  27. class ObjectGraphCalculator
  28. {
  29. private:
  30. ObjectGraph * target;
  31. const Nullkiller * ai;
  32. std::mutex syncLock;
  33. std::map<const CGHeroInstance *, HeroRole> actors;
  34. std::map<const CGHeroInstance *, const CGObjectInstance *> actorObjectMap;
  35. std::vector<std::unique_ptr<CGBoat>> temporaryBoats;
  36. std::vector<std::unique_ptr<CGHeroInstance>> temporaryActorHeroes;
  37. public:
  38. ObjectGraphCalculator(ObjectGraph * target, const Nullkiller * ai)
  39. :ai(ai), target(target), syncLock()
  40. {
  41. }
  42. void setGraphObjects()
  43. {
  44. for(auto obj : ai->memory->visitableObjs)
  45. {
  46. if(obj && obj->isVisitable() && obj->ID != Obj::HERO && obj->ID != Obj::EVENT)
  47. {
  48. addObjectActor(obj);
  49. }
  50. }
  51. for(auto town : ai->cb->getTownsInfo())
  52. {
  53. addObjectActor(town);
  54. }
  55. }
  56. void calculateConnections()
  57. {
  58. updatePaths();
  59. std::vector<AIPath> pathCache;
  60. foreach_tile_pos(ai->cb.get(), [this, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & pos)
  61. {
  62. calculateConnections(pos, pathCache);
  63. });
  64. removeExtraConnections();
  65. }
  66. float getNeighborConnectionsCost(const int3 & pos, std::vector<AIPath> & pathCache)
  67. {
  68. float neighborCost = std::numeric_limits<float>::max();
  69. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  70. {
  71. logAi->trace("Checking junction %s", pos.toString());
  72. }
  73. foreach_neighbour(
  74. ai->cb.get(),
  75. pos,
  76. [this, &neighborCost, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  77. {
  78. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  79. auto costTotal = this->getConnectionsCost(pathCache);
  80. if(costTotal.connectionsCount > 2 && costTotal.avg < neighborCost)
  81. {
  82. neighborCost = costTotal.avg;
  83. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  84. {
  85. logAi->trace("Better node found at %s", neighbor.toString());
  86. }
  87. }
  88. });
  89. return neighborCost;
  90. }
  91. void addMinimalDistanceJunctions()
  92. {
  93. pforeachTilePaths(ai->cb->getMapSize(), ai, [this](const int3 & pos, std::vector<AIPath> & paths)
  94. {
  95. if(target->hasNodeAt(pos))
  96. return;
  97. if(ai->cb->getGuardingCreaturePosition(pos).valid())
  98. return;
  99. ConnectionCostInfo currentCost = getConnectionsCost(paths);
  100. if(currentCost.connectionsCount <= 2)
  101. return;
  102. float neighborCost = getNeighborConnectionsCost(pos, paths);
  103. if(currentCost.avg < neighborCost)
  104. {
  105. addJunctionActor(pos);
  106. }
  107. });
  108. }
  109. private:
  110. void updatePaths()
  111. {
  112. PathfinderSettings ps;
  113. ps.mainTurnDistanceLimit = 5;
  114. ps.scoutTurnDistanceLimit = 1;
  115. ps.allowBypassObjects = false;
  116. ai->pathfinder->updatePaths(actors, ps);
  117. }
  118. void calculateConnections(const int3 & pos, std::vector<AIPath> & pathCache)
  119. {
  120. if(target->hasNodeAt(pos))
  121. {
  122. foreach_neighbour(
  123. ai->cb.get(),
  124. pos,
  125. [this, &pos, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  126. {
  127. if(target->hasNodeAt(neighbor))
  128. {
  129. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  130. for(auto & path : pathCache)
  131. {
  132. if(pos == path.targetHero->visitablePos())
  133. {
  134. target->tryAddConnection(pos, neighbor, path.movementCost(), path.getTotalDanger());
  135. }
  136. }
  137. }
  138. });
  139. return;
  140. }
  141. auto guardPos = ai->cb->getGuardingCreaturePosition(pos);
  142. ai->pathfinder->calculatePathInfo(pathCache, pos);
  143. for(AIPath & path1 : pathCache)
  144. {
  145. for(AIPath & path2 : pathCache)
  146. {
  147. if(path1.targetHero == path2.targetHero)
  148. continue;
  149. auto pos1 = path1.targetHero->visitablePos();
  150. auto pos2 = path2.targetHero->visitablePos();
  151. if(guardPos.valid() && guardPos != pos1 && guardPos != pos2)
  152. continue;
  153. auto obj1 = actorObjectMap[path1.targetHero];
  154. auto obj2 = actorObjectMap[path2.targetHero];
  155. auto tile1 = cb->getTile(pos1);
  156. auto tile2 = cb->getTile(pos2);
  157. if(tile2->isWater() && !tile1->isWater())
  158. {
  159. if(!cb->getTile(pos)->isWater())
  160. continue;
  161. if(obj1 && (obj1->ID != Obj::BOAT || obj1->ID != Obj::SHIPYARD))
  162. continue;
  163. }
  164. auto danger = ai->pathfinder->getStorage()->evaluateDanger(pos2, path1.targetHero, true);
  165. auto updated = target->tryAddConnection(
  166. pos1,
  167. pos2,
  168. path1.movementCost() + path2.movementCost(),
  169. danger);
  170. if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
  171. {
  172. logAi->trace(
  173. "Connected %s[%s] -> %s[%s] through [%s], cost %2f",
  174. obj1 ? obj1->getObjectName() : "J", pos1.toString(),
  175. obj2 ? obj2->getObjectName() : "J", pos2.toString(),
  176. pos.toString(),
  177. path1.movementCost() + path2.movementCost());
  178. }
  179. }
  180. }
  181. }
  182. bool isExtraConnection(float direct, float side1, float side2) const
  183. {
  184. float sideRatio = (side1 + side2) / direct;
  185. return sideRatio < 1.25f && direct > side1 && direct > side2;
  186. }
  187. void removeExtraConnections()
  188. {
  189. std::vector<std::pair<int3, int3>> connectionsToRemove;
  190. for(auto & actor : temporaryActorHeroes)
  191. {
  192. auto pos = actor->visitablePos();
  193. auto & currentNode = target->getNode(pos);
  194. target->iterateConnections(pos, [this, &pos, &connectionsToRemove, &currentNode](int3 n1, ObjectLink o1)
  195. {
  196. target->iterateConnections(n1, [&pos, &o1, &currentNode, &connectionsToRemove, this](int3 n2, ObjectLink o2)
  197. {
  198. auto direct = currentNode.connections.find(n2);
  199. if(direct != currentNode.connections.end() && isExtraConnection(direct->second.cost, o1.cost, o2.cost))
  200. {
  201. connectionsToRemove.push_back({pos, n2});
  202. }
  203. });
  204. });
  205. }
  206. vstd::removeDuplicates(connectionsToRemove);
  207. for(auto & c : connectionsToRemove)
  208. {
  209. target->removeConnection(c.first, c.second);
  210. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  211. {
  212. logAi->trace("Remove ineffective connection %s->%s", c.first.toString(), c.second.toString());
  213. }
  214. }
  215. }
  216. void addObjectActor(const CGObjectInstance * obj)
  217. {
  218. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(obj->cb)).get();
  219. CRandomGenerator rng;
  220. auto visitablePos = obj->visitablePos();
  221. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  222. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  223. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  224. objectActor->initObj(rng);
  225. if(cb->getTile(visitablePos)->isWater())
  226. {
  227. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  228. }
  229. assert(objectActor->visitablePos() == visitablePos);
  230. actorObjectMap[objectActor] = obj;
  231. actors[objectActor] = obj->ID == Obj::TOWN || obj->ID == Obj::SHIPYARD ? HeroRole::MAIN : HeroRole::SCOUT;
  232. target->addObject(obj);
  233. }
  234. void addJunctionActor(const int3 & visitablePos)
  235. {
  236. std::lock_guard<std::mutex> lock(syncLock);
  237. auto internalCb = temporaryActorHeroes.front()->cb;
  238. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(internalCb)).get();
  239. CRandomGenerator rng;
  240. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  241. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  242. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  243. objectActor->initObj(rng);
  244. if(ai->cb->getTile(visitablePos)->isWater())
  245. {
  246. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  247. }
  248. assert(objectActor->visitablePos() == visitablePos);
  249. actorObjectMap[objectActor] = nullptr;
  250. actors[objectActor] = HeroRole::SCOUT;
  251. target->registerJunction(visitablePos);
  252. }
  253. ConnectionCostInfo getConnectionsCost(std::vector<AIPath> & paths) const
  254. {
  255. std::map<int3, float> costs;
  256. for(auto & path : paths)
  257. {
  258. auto fromPos = path.targetHero->visitablePos();
  259. auto cost = costs.find(fromPos);
  260. if(cost == costs.end())
  261. {
  262. costs.emplace(fromPos, path.movementCost());
  263. }
  264. else
  265. {
  266. if(path.movementCost() < cost->second)
  267. {
  268. costs[fromPos] = path.movementCost();
  269. }
  270. }
  271. }
  272. ConnectionCostInfo result;
  273. for(auto & cost : costs)
  274. {
  275. result.totalCost += cost.second;
  276. result.connectionsCount++;
  277. }
  278. if(result.connectionsCount)
  279. {
  280. result.avg = result.totalCost / result.connectionsCount;
  281. }
  282. return result;
  283. }
  284. };
  285. bool ObjectGraph::tryAddConnection(
  286. const int3 & from,
  287. const int3 & to,
  288. float cost,
  289. uint64_t danger)
  290. {
  291. return nodes[from].connections[to].update(cost, danger);
  292. }
  293. void ObjectGraph::removeConnection(const int3 & from, const int3 & to)
  294. {
  295. nodes[from].connections.erase(to);
  296. }
  297. void ObjectGraph::updateGraph(const Nullkiller * ai)
  298. {
  299. auto cb = ai->cb;
  300. ObjectGraphCalculator calculator(this, ai);
  301. calculator.setGraphObjects();
  302. calculator.calculateConnections();
  303. calculator.addMinimalDistanceJunctions();
  304. calculator.calculateConnections();
  305. if(NKAI_GRAPH_TRACE_LEVEL >= 1)
  306. dumpToLog("graph");
  307. }
  308. void ObjectGraph::addObject(const CGObjectInstance * obj)
  309. {
  310. nodes[obj->visitablePos()].init(obj);
  311. }
  312. void ObjectGraph::registerJunction(const int3 & pos)
  313. {
  314. nodes[pos].initJunction();
  315. }
  316. void ObjectGraph::removeObject(const CGObjectInstance * obj)
  317. {
  318. nodes[obj->visitablePos()].objectExists = false;
  319. if(obj->ID == Obj::BOAT)
  320. {
  321. vstd::erase_if(nodes[obj->visitablePos()].connections, [&](const std::pair<int3, ObjectLink> & link) -> bool
  322. {
  323. auto tile = cb->getTile(link.first, false);
  324. return tile && tile->isWater();
  325. });
  326. }
  327. }
  328. void ObjectGraph::connectHeroes(const Nullkiller * ai)
  329. {
  330. for(auto obj : ai->memory->visitableObjs)
  331. {
  332. if(obj && obj->ID == Obj::HERO)
  333. {
  334. addObject(obj);
  335. }
  336. }
  337. for(auto & node : nodes)
  338. {
  339. auto pos = node.first;
  340. auto paths = ai->pathfinder->getPathInfo(pos);
  341. for(AIPath & path : paths)
  342. {
  343. if(path.getFirstBlockedAction())
  344. continue;
  345. auto heroPos = path.targetHero->visitablePos();
  346. nodes[pos].connections[heroPos].update(
  347. path.movementCost(),
  348. path.getPathDanger());
  349. nodes[heroPos].connections[pos].update(
  350. path.movementCost(),
  351. path.getPathDanger());
  352. }
  353. }
  354. }
  355. void ObjectGraph::dumpToLog(std::string visualKey) const
  356. {
  357. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  358. {
  359. for(auto & tile : nodes)
  360. {
  361. for(auto & node : tile.second.connections)
  362. {
  363. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  364. {
  365. logAi->trace(
  366. "%s -> %s: %f !%d",
  367. node.first.toString(),
  368. tile.first.toString(),
  369. node.second.cost,
  370. node.second.danger);
  371. }
  372. logBuilder.addLine(tile.first, node.first);
  373. }
  374. }
  375. });
  376. }
  377. bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
  378. {
  379. return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
  380. }
  381. GraphPaths::GraphPaths()
  382. : visualKey(""), graph(), pathNodes()
  383. {
  384. }
  385. void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai)
  386. {
  387. graph.copyFrom(*ai->baseGraph);
  388. graph.connectHeroes(ai);
  389. visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
  390. pathNodes.clear();
  391. GraphNodeComparer cmp(pathNodes);
  392. GraphPathNode::TFibHeap pq(cmp);
  393. pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
  394. pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
  395. while(!pq.empty())
  396. {
  397. GraphPathNodePointer pos = pq.top();
  398. pq.pop();
  399. auto & node = getOrCreateNode(pos);
  400. std::shared_ptr<SpecialAction> transitionAction;
  401. if(node.obj)
  402. {
  403. if(node.obj->ID == Obj::QUEST_GUARD
  404. || node.obj->ID == Obj::BORDERGUARD
  405. || node.obj->ID == Obj::BORDER_GATE)
  406. {
  407. auto questObj = dynamic_cast<const IQuestObject *>(node.obj);
  408. auto questInfo = QuestInfo(questObj->quest, node.obj, pos.coord);
  409. if(node.obj->ID == Obj::QUEST_GUARD
  410. && questObj->quest->mission == Rewardable::Limiter{}
  411. && questObj->quest->killTarget == ObjectInstanceID::NONE)
  412. {
  413. continue;
  414. }
  415. auto questAction = std::make_shared<AIPathfinding::QuestAction>(questInfo);
  416. if(!questAction->canAct(targetHero))
  417. {
  418. transitionAction = questAction;
  419. }
  420. }
  421. }
  422. node.isInQueue = false;
  423. graph.iterateConnections(pos.coord, [this, ai, &pos, &node, &transitionAction, &pq](int3 target, ObjectLink o)
  424. {
  425. auto targetNodeType = o.danger || transitionAction ? GrapthPathNodeType::BATTLE : pos.nodeType;
  426. auto targetPointer = GraphPathNodePointer(target, targetNodeType);
  427. auto & targetNode = getOrCreateNode(targetPointer);
  428. if(targetNode.tryUpdate(pos, node, o))
  429. {
  430. targetNode.specialAction = transitionAction;
  431. auto targetGraphNode = graph.getNode(target);
  432. if(targetGraphNode.objID.hasValue())
  433. {
  434. targetNode.obj = ai->cb->getObj(targetGraphNode.objID, false);
  435. if(targetNode.obj && targetNode.obj->ID == Obj::HERO)
  436. return;
  437. }
  438. if(targetNode.isInQueue)
  439. {
  440. pq.increase(targetNode.handle);
  441. }
  442. else
  443. {
  444. targetNode.handle = pq.emplace(targetPointer);
  445. targetNode.isInQueue = true;
  446. }
  447. }
  448. });
  449. }
  450. }
  451. void GraphPaths::dumpToLog() const
  452. {
  453. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  454. {
  455. for(auto & tile : pathNodes)
  456. {
  457. for(auto & node : tile.second)
  458. {
  459. if(!node.previous.valid())
  460. continue;
  461. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  462. {
  463. logAi->trace(
  464. "%s -> %s: %f !%d",
  465. node.previous.coord.toString(),
  466. tile.first.toString(),
  467. node.cost,
  468. node.danger);
  469. }
  470. logBuilder.addLine(node.previous.coord, tile.first);
  471. }
  472. }
  473. });
  474. }
  475. bool GraphPathNode::tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link)
  476. {
  477. auto newCost = prev.cost + link.cost;
  478. if(newCost < cost)
  479. {
  480. previous = pos;
  481. danger = prev.danger + link.danger;
  482. cost = newCost;
  483. return true;
  484. }
  485. return false;
  486. }
  487. void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  488. {
  489. auto nodes = pathNodes.find(tile);
  490. if(nodes == pathNodes.end())
  491. return;
  492. for(auto & node : nodes->second)
  493. {
  494. if(!node.reachable())
  495. continue;
  496. std::vector<GraphPathNodePointer> tilesToPass;
  497. uint64_t danger = node.danger;
  498. float cost = node.cost;
  499. bool allowBattle = false;
  500. auto current = GraphPathNodePointer(nodes->first, node.nodeType);
  501. while(true)
  502. {
  503. auto currentTile = pathNodes.find(current.coord);
  504. if(currentTile == pathNodes.end())
  505. break;
  506. auto currentNode = currentTile->second[current.nodeType];
  507. if(!currentNode.previous.valid())
  508. break;
  509. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  510. vstd::amax(danger, currentNode.danger);
  511. vstd::amax(cost, currentNode.cost);
  512. tilesToPass.push_back(current);
  513. if(currentNode.cost < 2.0f)
  514. break;
  515. current = currentNode.previous;
  516. }
  517. if(tilesToPass.empty())
  518. continue;
  519. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  520. for(auto & path : entryPaths)
  521. {
  522. if(path.targetHero != hero)
  523. continue;
  524. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  525. {
  526. AIPathNodeInfo n;
  527. n.coord = graphTile->coord;
  528. n.cost = cost;
  529. n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
  530. n.danger = danger;
  531. n.targetHero = hero;
  532. n.parentIndex = -1;
  533. n.specialAction = getNode(*graphTile).specialAction;
  534. for(auto & node : path.nodes)
  535. {
  536. node.parentIndex++;
  537. }
  538. path.nodes.insert(path.nodes.begin(), n);
  539. }
  540. path.armyLoss += ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  541. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  542. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  543. paths.push_back(path);
  544. }
  545. }
  546. }
  547. void GraphPaths::quickAddChainInfoWithBlocker(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  548. {
  549. auto nodes = pathNodes.find(tile);
  550. if(nodes == pathNodes.end())
  551. return;
  552. for(auto & targetNode : nodes->second)
  553. {
  554. if(!targetNode.reachable())
  555. continue;
  556. std::vector<GraphPathNodePointer> tilesToPass;
  557. uint64_t danger = targetNode.danger;
  558. float cost = targetNode.cost;
  559. bool allowBattle = false;
  560. auto current = GraphPathNodePointer(nodes->first, targetNode.nodeType);
  561. while(true)
  562. {
  563. auto currentTile = pathNodes.find(current.coord);
  564. if(currentTile == pathNodes.end())
  565. break;
  566. auto currentNode = currentTile->second[current.nodeType];
  567. if(!currentNode.previous.valid())
  568. break;
  569. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  570. vstd::amax(danger, currentNode.danger);
  571. vstd::amax(cost, currentNode.cost);
  572. tilesToPass.push_back(current);
  573. if(currentNode.cost < 2.0f)
  574. break;
  575. current = currentNode.previous;
  576. }
  577. if(tilesToPass.empty())
  578. continue;
  579. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  580. for(auto & entryPath : entryPaths)
  581. {
  582. if(entryPath.targetHero != hero)
  583. continue;
  584. auto & path = paths.emplace_back();
  585. path.targetHero = entryPath.targetHero;
  586. path.heroArmy = entryPath.heroArmy;
  587. path.exchangeCount = entryPath.exchangeCount;
  588. path.armyLoss = entryPath.armyLoss + ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  589. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  590. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  591. AIPathNodeInfo n;
  592. n.targetHero = hero;
  593. n.parentIndex = -1;
  594. // final node
  595. n.coord = tile;
  596. n.cost = targetNode.cost;
  597. n.danger = targetNode.danger;
  598. n.parentIndex = path.nodes.size();
  599. path.nodes.push_back(n);
  600. for(auto entryNode = entryPath.nodes.rbegin(); entryNode != entryPath.nodes.rend(); entryNode++)
  601. {
  602. auto blocker = ai->objectClusterizer->getBlocker(*entryNode);
  603. if(blocker)
  604. {
  605. // blocker node
  606. path.nodes.push_back(*entryNode);
  607. path.nodes.back().parentIndex = path.nodes.size() - 1;
  608. break;
  609. }
  610. }
  611. if(!path.nodes.empty())
  612. break;
  613. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  614. {
  615. auto & node = getNode(*graphTile);
  616. n.coord = graphTile->coord;
  617. n.cost = node.cost;
  618. n.turns = static_cast<ui8>(node.cost);
  619. n.danger = node.danger;
  620. n.specialAction = node.specialAction;
  621. n.parentIndex = path.nodes.size();
  622. auto blocker = ai->objectClusterizer->getBlocker(n);
  623. if(!blocker)
  624. continue;
  625. // blocker node
  626. path.nodes.push_back(n);
  627. break;
  628. }
  629. }
  630. }
  631. }
  632. }