ConnectionsPlacer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. * ConnectionsPlacer.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 "ConnectionsPlacer.h"
  12. #include "../CMapGenerator.h"
  13. #include "../RmgMap.h"
  14. #include "../../TerrainHandler.h"
  15. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  16. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  17. #include "../../mapping/CMapEditManager.h"
  18. #include "../RmgObject.h"
  19. #include "ObjectManager.h"
  20. #include "../Functions.h"
  21. #include "RoadPlacer.h"
  22. #include "../TileInfo.h"
  23. #include "WaterAdopter.h"
  24. #include "WaterProxy.h"
  25. #include "TownPlacer.h"
  26. #include <boost/interprocess/sync/scoped_lock.hpp>
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. void ConnectionsPlacer::process()
  29. {
  30. collectNeighbourZones();
  31. auto diningPhilosophers = [this](std::function<void(const rmg::ZoneConnection&)> f)
  32. {
  33. for (auto& c : dConnections)
  34. {
  35. if (c.getZoneA() != zone.getId() && c.getZoneB() != zone.getId())
  36. continue;
  37. auto otherZone = map.getZones().at(c.getZoneB());
  38. auto* cp = otherZone->getModificator<ConnectionsPlacer>();
  39. while (cp)
  40. {
  41. RecursiveLock lock1(externalAccessMutex, boost::try_to_lock_t{});
  42. RecursiveLock lock2(cp->externalAccessMutex, boost::try_to_lock_t{});
  43. if (lock1.owns_lock() && lock2.owns_lock())
  44. {
  45. if (!vstd::contains(dCompleted, c))
  46. {
  47. f(c);
  48. }
  49. break;
  50. }
  51. }
  52. }
  53. };
  54. diningPhilosophers([this](const rmg::ZoneConnection& c)
  55. {
  56. selfSideDirectConnection(c);
  57. });
  58. createBorder();
  59. diningPhilosophers([this](const rmg::ZoneConnection& c)
  60. {
  61. selfSideIndirectConnection(c);
  62. });
  63. }
  64. void ConnectionsPlacer::init()
  65. {
  66. DEPENDENCY(WaterAdopter);
  67. DEPENDENCY(TownPlacer);
  68. POSTFUNCTION(RoadPlacer);
  69. POSTFUNCTION(ObjectManager);
  70. for(auto c : map.getMapGenOptions().getMapTemplate()->getConnections())
  71. addConnection(c);
  72. }
  73. void ConnectionsPlacer::addConnection(const rmg::ZoneConnection& connection)
  74. {
  75. dConnections.push_back(connection);
  76. }
  77. void ConnectionsPlacer::otherSideConnection(const rmg::ZoneConnection & connection)
  78. {
  79. dCompleted.push_back(connection);
  80. }
  81. void ConnectionsPlacer::selfSideDirectConnection(const rmg::ZoneConnection & connection)
  82. {
  83. bool success = false;
  84. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  85. auto & otherZone = map.getZones().at(otherZoneId);
  86. //1. Try to make direct connection
  87. //Do if it's not prohibited by terrain settings
  88. const auto * ourTerrain = VLC->terrainTypeHandler->getById(zone.getTerrainType());
  89. const auto * otherTerrain = VLC->terrainTypeHandler->getById(otherZone->getTerrainType());
  90. bool directProhibited = vstd::contains(ourTerrain->prohibitTransitions, otherZone->getTerrainType())
  91. || vstd::contains(otherTerrain->prohibitTransitions, zone.getTerrainType());
  92. auto directConnectionIterator = dNeighbourZones.find(otherZoneId);
  93. if(!directProhibited && directConnectionIterator != dNeighbourZones.end())
  94. {
  95. int3 guardPos(-1, -1, -1);
  96. int3 borderPos;
  97. while(!directConnectionIterator->second.empty())
  98. {
  99. borderPos = *RandomGeneratorUtil::nextItem(directConnectionIterator->second, zone.getRand());
  100. guardPos = zone.areaPossible().nearest(borderPos);
  101. assert(borderPos != guardPos);
  102. float dist = map.getTileInfo(guardPos).getNearestObjectDistance();
  103. if (dist >= 3) //Don't place guards at adjacent tiles
  104. {
  105. auto safetyGap = rmg::Area({ guardPos });
  106. safetyGap.unite(safetyGap.getBorderOutside());
  107. safetyGap.intersect(zone.areaPossible());
  108. if (!safetyGap.empty())
  109. {
  110. safetyGap.intersect(otherZone->areaPossible());
  111. if (safetyGap.empty())
  112. break; //successfull position
  113. }
  114. }
  115. //failed position
  116. directConnectionIterator->second.erase(borderPos);
  117. guardPos = int3(-1, -1, -1);
  118. }
  119. if(guardPos.valid())
  120. {
  121. assert(zone.getModificator<ObjectManager>());
  122. auto & manager = *zone.getModificator<ObjectManager>();
  123. auto * monsterType = manager.chooseGuard(connection.getGuardStrength(), true);
  124. rmg::Area border(zone.getArea().getBorder());
  125. border.unite(otherZone->getArea().getBorder());
  126. auto costFunction = [&border](const int3 & s, const int3 & d)
  127. {
  128. return 1.f / (1.f + border.distanceSqr(d));
  129. };
  130. auto ourArea = zone.areaPossible() + zone.freePaths();
  131. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  132. theirArea.add(guardPos);
  133. rmg::Path ourPath(ourArea);
  134. rmg::Path theirPath(theirArea);
  135. ourPath.connect(zone.freePaths());
  136. ourPath = ourPath.search(guardPos, true, costFunction);
  137. theirPath.connect(otherZone->freePaths());
  138. theirPath = theirPath.search(guardPos, true, costFunction);
  139. if(ourPath.valid() && theirPath.valid())
  140. {
  141. zone.connectPath(ourPath);
  142. otherZone->connectPath(theirPath);
  143. if(monsterType)
  144. {
  145. rmg::Object monster(*monsterType);
  146. monster.setPosition(guardPos);
  147. manager.placeObject(monster, false, true);
  148. //Place objects away from the monster in the other zone, too
  149. otherZone->getModificator<ObjectManager>()->updateDistances(monster);
  150. }
  151. else
  152. {
  153. zone.areaPossible().erase(guardPos);
  154. zone.freePaths().add(guardPos);
  155. map.setOccupied(guardPos, ETileType::FREE);
  156. }
  157. assert(zone.getModificator<RoadPlacer>());
  158. zone.getModificator<RoadPlacer>()->addRoadNode(guardPos);
  159. assert(otherZone->getModificator<RoadPlacer>());
  160. otherZone->getModificator<RoadPlacer>()->addRoadNode(borderPos);
  161. assert(otherZone->getModificator<ConnectionsPlacer>());
  162. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  163. success = true;
  164. }
  165. }
  166. }
  167. //2. connect via water
  168. bool waterMode = map.getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  169. if(waterMode && zone.isUnderground() == otherZone->isUnderground())
  170. {
  171. if(generator.getZoneWater() && generator.getZoneWater()->getModificator<WaterProxy>())
  172. {
  173. if(generator.getZoneWater()->getModificator<WaterProxy>()->waterKeepConnection(connection.getZoneA(), connection.getZoneB()))
  174. {
  175. assert(otherZone->getModificator<ConnectionsPlacer>());
  176. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  177. success = true;
  178. }
  179. }
  180. }
  181. if(success)
  182. dCompleted.push_back(connection);
  183. }
  184. void ConnectionsPlacer::selfSideIndirectConnection(const rmg::ZoneConnection & connection)
  185. {
  186. bool success = false;
  187. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  188. auto & otherZone = map.getZones().at(otherZoneId);
  189. //3. place subterrain gates
  190. if(zone.isUnderground() != otherZone->isUnderground())
  191. {
  192. int3 zShift(0, 0, zone.getPos().z - otherZone->getPos().z);
  193. auto commonArea = zone.areaPossible() * (otherZone->areaPossible() + zShift);
  194. if(!commonArea.empty())
  195. {
  196. assert(zone.getModificator<ObjectManager>());
  197. auto & manager = *zone.getModificator<ObjectManager>();
  198. assert(otherZone->getModificator<ObjectManager>());
  199. auto & managerOther = *otherZone->getModificator<ObjectManager>();
  200. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  201. auto * gate1 = factory->create();
  202. auto * gate2 = factory->create();
  203. rmg::Object rmgGate1(*gate1);
  204. rmg::Object rmgGate2(*gate2);
  205. rmgGate1.setTemplate(zone.getTerrainType());
  206. rmgGate2.setTemplate(otherZone->getTerrainType());
  207. bool guarded1 = manager.addGuard(rmgGate1, connection.getGuardStrength(), true);
  208. bool guarded2 = managerOther.addGuard(rmgGate2, connection.getGuardStrength(), true);
  209. int minDist = 3;
  210. std::scoped_lock doubleLock(zone.areaMutex, otherZone->areaMutex);
  211. rmg::Path path2(otherZone->area());
  212. rmg::Path path1 = manager.placeAndConnectObject(commonArea, rmgGate1, [this, minDist, &path2, &rmgGate1, &zShift, guarded2, &managerOther, &rmgGate2 ](const int3 & tile)
  213. {
  214. auto ti = map.getTileInfo(tile);
  215. auto otherTi = map.getTileInfo(tile - zShift);
  216. float dist = ti.getNearestObjectDistance();
  217. float otherDist = otherTi.getNearestObjectDistance();
  218. if(dist < minDist || otherDist < minDist)
  219. return -1.f;
  220. rmg::Area toPlace(rmgGate1.getArea() + rmgGate1.getAccessibleArea());
  221. toPlace.translate(-zShift);
  222. path2 = managerOther.placeAndConnectObject(toPlace, rmgGate2, minDist, guarded2, true, ObjectManager::OptimizeType::NONE);
  223. return path2.valid() ? (dist * otherDist) : -1.f;
  224. }, guarded1, true, ObjectManager::OptimizeType::DISTANCE);
  225. if(path1.valid() && path2.valid())
  226. {
  227. zone.connectPath(path1);
  228. otherZone->connectPath(path2);
  229. manager.placeObject(rmgGate1, guarded1, true);
  230. managerOther.placeObject(rmgGate2, guarded2, true);
  231. assert(otherZone->getModificator<ConnectionsPlacer>());
  232. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  233. success = true;
  234. }
  235. }
  236. }
  237. //4. place monoliths/portals
  238. if(!success)
  239. {
  240. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, generator.getNextMonlithIndex());
  241. auto * teleport1 = factory->create();
  242. auto * teleport2 = factory->create();
  243. zone.getModificator<ObjectManager>()->addRequiredObject(teleport1, connection.getGuardStrength());
  244. otherZone->getModificator<ObjectManager>()->addRequiredObject(teleport2, connection.getGuardStrength());
  245. assert(otherZone->getModificator<ConnectionsPlacer>());
  246. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  247. success = true;
  248. }
  249. if(success)
  250. dCompleted.push_back(connection);
  251. }
  252. void ConnectionsPlacer::collectNeighbourZones()
  253. {
  254. auto border = zone.area().getBorderOutside();
  255. for(const auto & i : border)
  256. {
  257. if(!map.isOnMap(i))
  258. continue;
  259. auto zid = map.getZoneID(i);
  260. assert(zid != zone.getId());
  261. dNeighbourZones[zid].insert(i);
  262. }
  263. }
  264. void ConnectionsPlacer::createBorder()
  265. {
  266. rmg::Area borderArea(zone.getArea().getBorder());
  267. rmg::Area borderOutsideArea(zone.getArea().getBorderOutside());
  268. auto blockBorder = borderArea.getSubarea([this, &borderOutsideArea](const int3 & t)
  269. {
  270. auto tile = borderOutsideArea.nearest(t);
  271. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getType() != ETemplateZoneType::WATER;
  272. });
  273. Zone::Lock lock(zone.areaMutex); //Protect from erasing same tiles again
  274. for(const auto & tile : blockBorder.getTilesVector())
  275. {
  276. if(map.isPossible(tile))
  277. {
  278. map.setOccupied(tile, ETileType::BLOCKED);
  279. zone.areaPossible().erase(tile);
  280. }
  281. map.foreachDirectNeighbour(tile, [this](int3 &nearbyPos)
  282. {
  283. if(map.isPossible(nearbyPos) && map.getZoneID(nearbyPos) == zone.getId())
  284. {
  285. map.setOccupied(nearbyPos, ETileType::BLOCKED);
  286. zone.areaPossible().erase(nearbyPos);
  287. }
  288. });
  289. }
  290. }
  291. VCMI_LIB_NAMESPACE_END