ObjectGraph.cpp 22 KB

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