AIPathfinder.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * AIPathfinder.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 "AIPathfinder.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../CCallback.h"
  14. #include "../../../lib/mapping/CMap.h"
  15. std::vector<std::shared_ptr<AINodeStorage>> AIPathfinder::storagePool;
  16. std::map<HeroPtr, std::shared_ptr<AINodeStorage>> AIPathfinder::storageMap;
  17. boost::mutex AIPathfinder::storageMutex;
  18. AIPathfinder::AIPathfinder(CPlayerSpecificInfoCallback * cb, VCAI * ai)
  19. :cb(cb), ai(ai)
  20. {
  21. }
  22. void AIPathfinder::clear()
  23. {
  24. boost::unique_lock<boost::mutex> storageLock(storageMutex);
  25. storageMap.clear();
  26. }
  27. void AIPathfinder::init()
  28. {
  29. boost::unique_lock<boost::mutex> storageLock(storageMutex);
  30. storagePool.clear();
  31. storageMap.clear();
  32. }
  33. bool AIPathfinder::isTileAccessible(HeroPtr hero, int3 tile)
  34. {
  35. boost::unique_lock<boost::mutex> storageLock(storageMutex);
  36. std::shared_ptr<AINodeStorage> nodeStorage = getOrCreateStorage(hero);
  37. return nodeStorage->isTileAccessible(tile, EPathfindingLayer::LAND)
  38. || nodeStorage->isTileAccessible(tile, EPathfindingLayer::SAIL);
  39. }
  40. std::vector<AIPath> AIPathfinder::getPathInfo(HeroPtr hero, int3 tile)
  41. {
  42. boost::unique_lock<boost::mutex> storageLock(storageMutex);
  43. std::shared_ptr<AINodeStorage> nodeStorage = getOrCreateStorage(hero);
  44. const TerrainTile * tileInfo = cb->getTile(tile, false);
  45. if(!tileInfo)
  46. {
  47. return std::vector<AIPath>();
  48. }
  49. return nodeStorage->getChainInfo(tile, !tileInfo->isWater());
  50. }
  51. std::shared_ptr<AINodeStorage> AIPathfinder::getOrCreateStorage(HeroPtr hero)
  52. {
  53. std::shared_ptr<AINodeStorage> nodeStorage;
  54. if(!vstd::contains(storageMap, hero))
  55. {
  56. logAi->debug("Recalculate paths for %s", hero->name);
  57. if(storageMap.size() < storagePool.size())
  58. {
  59. nodeStorage = storagePool.at(storageMap.size());
  60. }
  61. else
  62. {
  63. nodeStorage = std::make_shared<AINodeStorage>(cb->getMapSize());
  64. storagePool.push_back(nodeStorage);
  65. }
  66. storageMap[hero] = nodeStorage;
  67. nodeStorage->setHero(hero.get());
  68. auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, nodeStorage);
  69. cb->calculatePaths(config, hero.get());
  70. }
  71. else
  72. {
  73. nodeStorage = storageMap.at(hero);
  74. }
  75. return nodeStorage;
  76. }