ObjectGraph.cpp 16 KB

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