ObjectGraph.cpp 19 KB

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