ConnectionsPlacer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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()->getConnectedZoneIds())
  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 (directConnectionIterator != dNeighbourZones.end())
  94. {
  95. if (connection.getConnectionType() == EConnectionType::EConnectionType::WIDE)
  96. {
  97. for (auto borderPos : directConnectionIterator->second)
  98. {
  99. //TODO: Refactor common code with direct connection
  100. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  101. assert(borderPos != potentialPos);
  102. auto safetyGap = rmg::Area({ potentialPos });
  103. safetyGap.unite(safetyGap.getBorderOutside());
  104. safetyGap.intersect(zone.areaPossible());
  105. if (!safetyGap.empty())
  106. {
  107. safetyGap.intersect(otherZone->areaPossible());
  108. if (safetyGap.empty())
  109. {
  110. rmg::Area border(zone.getArea().getBorder());
  111. border.unite(otherZone->getArea().getBorder());
  112. auto costFunction = [&border](const int3& s, const int3& d)
  113. {
  114. return 1.f / (1.f + border.distanceSqr(d));
  115. };
  116. auto ourArea = zone.areaPossible() + zone.freePaths();
  117. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  118. theirArea.add(potentialPos);
  119. rmg::Path ourPath(ourArea);
  120. rmg::Path theirPath(theirArea);
  121. ourPath.connect(zone.freePaths());
  122. ourPath = ourPath.search(potentialPos, true, costFunction);
  123. theirPath.connect(otherZone->freePaths());
  124. theirPath = theirPath.search(potentialPos, true, costFunction);
  125. if (ourPath.valid() && theirPath.valid())
  126. {
  127. zone.connectPath(ourPath);
  128. otherZone->connectPath(theirPath);
  129. otherZone->getModificator<ObjectManager>()->updateDistances(potentialPos);
  130. success = true;
  131. break;
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }
  138. if (connection.getConnectionType() == EConnectionType::EConnectionType::FICTIVE ||
  139. connection.getConnectionType() == EConnectionType::EConnectionType::REPULSIVE)
  140. {
  141. //Fictive or repulsive connections are not real, take no action
  142. dCompleted.push_back(connection);
  143. return;
  144. }
  145. float maxDist = -10e6;
  146. if(!success && !directProhibited && directConnectionIterator != dNeighbourZones.end())
  147. {
  148. int3 guardPos(-1, -1, -1);
  149. int3 roadNode;
  150. for (auto borderPos : directConnectionIterator->second)
  151. {
  152. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  153. assert(borderPos != potentialPos);
  154. //Take into account distance to objects from both sides
  155. float dist = std::min(map.getTileInfo(potentialPos).getNearestObjectDistance(),
  156. map.getTileInfo(borderPos).getNearestObjectDistance());
  157. if (dist > 3) //Don't place guards at adjacent tiles
  158. {
  159. auto safetyGap = rmg::Area({ potentialPos });
  160. safetyGap.unite(safetyGap.getBorderOutside());
  161. safetyGap.intersect(zone.areaPossible());
  162. if (!safetyGap.empty())
  163. {
  164. safetyGap.intersect(otherZone->areaPossible());
  165. if (safetyGap.empty())
  166. {
  167. float distanceToCenter = zone.getPos().dist2d(potentialPos) * otherZone->getPos().dist2d(potentialPos);
  168. auto localDist = (dist - distanceToCenter) * //Prefer close to zone center
  169. (std::max(distanceToCenter, dist) / std::min(distanceToCenter, dist));
  170. //Distance to center dominates and is negative, so imbalanced proportions will result in huge penalty
  171. if (localDist > maxDist)
  172. {
  173. maxDist = localDist;
  174. guardPos = potentialPos;
  175. roadNode = borderPos;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. if(guardPos.valid())
  182. {
  183. assert(zone.getModificator<ObjectManager>());
  184. auto & manager = *zone.getModificator<ObjectManager>();
  185. auto * monsterType = manager.chooseGuard(connection.getGuardStrength(), true);
  186. rmg::Area border(zone.getArea().getBorder());
  187. border.unite(otherZone->getArea().getBorder());
  188. auto costFunction = [&border](const int3 & s, const int3 & d)
  189. {
  190. return 1.f / (1.f + border.distanceSqr(d));
  191. };
  192. auto ourArea = zone.areaPossible() + zone.freePaths();
  193. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  194. theirArea.add(guardPos);
  195. rmg::Path ourPath(ourArea);
  196. rmg::Path theirPath(theirArea);
  197. ourPath.connect(zone.freePaths());
  198. ourPath = ourPath.search(guardPos, true, costFunction);
  199. theirPath.connect(otherZone->freePaths());
  200. theirPath = theirPath.search(guardPos, true, costFunction);
  201. if(ourPath.valid() && theirPath.valid())
  202. {
  203. zone.connectPath(ourPath);
  204. otherZone->connectPath(theirPath);
  205. if(monsterType)
  206. {
  207. rmg::Object monster(*monsterType);
  208. monster.setPosition(guardPos);
  209. manager.placeObject(monster, false, true);
  210. //Place objects away from the monster in the other zone, too
  211. otherZone->getModificator<ObjectManager>()->updateDistances(monster);
  212. }
  213. else
  214. {
  215. //Update distances from empty passage, too
  216. zone.areaPossible().erase(guardPos);
  217. zone.freePaths().add(guardPos);
  218. map.setOccupied(guardPos, ETileType::FREE);
  219. manager.updateDistances(guardPos);
  220. otherZone->getModificator<ObjectManager>()->updateDistances(guardPos);
  221. }
  222. assert(zone.getModificator<RoadPlacer>());
  223. zone.getModificator<RoadPlacer>()->addRoadNode(guardPos);
  224. assert(otherZone->getModificator<RoadPlacer>());
  225. otherZone->getModificator<RoadPlacer>()->addRoadNode(roadNode);
  226. assert(otherZone->getModificator<ConnectionsPlacer>());
  227. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  228. success = true;
  229. }
  230. }
  231. }
  232. //2. connect via water
  233. bool waterMode = map.getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  234. if(waterMode && zone.isUnderground() == otherZone->isUnderground())
  235. {
  236. if(generator.getZoneWater() && generator.getZoneWater()->getModificator<WaterProxy>())
  237. {
  238. if(generator.getZoneWater()->getModificator<WaterProxy>()->waterKeepConnection(connection.getZoneA(), connection.getZoneB()))
  239. {
  240. assert(otherZone->getModificator<ConnectionsPlacer>());
  241. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  242. success = true;
  243. }
  244. }
  245. }
  246. if(success)
  247. dCompleted.push_back(connection);
  248. }
  249. void ConnectionsPlacer::selfSideIndirectConnection(const rmg::ZoneConnection & connection)
  250. {
  251. bool success = false;
  252. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  253. auto & otherZone = map.getZones().at(otherZoneId);
  254. //3. place subterrain gates
  255. if(zone.isUnderground() != otherZone->isUnderground())
  256. {
  257. int3 zShift(0, 0, zone.getPos().z - otherZone->getPos().z);
  258. auto commonArea = zone.areaPossible() * (otherZone->areaPossible() + zShift);
  259. if(!commonArea.empty())
  260. {
  261. assert(zone.getModificator<ObjectManager>());
  262. auto & manager = *zone.getModificator<ObjectManager>();
  263. assert(otherZone->getModificator<ObjectManager>());
  264. auto & managerOther = *otherZone->getModificator<ObjectManager>();
  265. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  266. auto * gate1 = factory->create();
  267. auto * gate2 = factory->create();
  268. rmg::Object rmgGate1(*gate1);
  269. rmg::Object rmgGate2(*gate2);
  270. rmgGate1.setTemplate(zone.getTerrainType());
  271. rmgGate2.setTemplate(otherZone->getTerrainType());
  272. bool guarded1 = manager.addGuard(rmgGate1, connection.getGuardStrength(), true);
  273. bool guarded2 = managerOther.addGuard(rmgGate2, connection.getGuardStrength(), true);
  274. int minDist = 3;
  275. std::scoped_lock doubleLock(zone.areaMutex, otherZone->areaMutex);
  276. rmg::Path path2(otherZone->area());
  277. rmg::Path path1 = manager.placeAndConnectObject(commonArea, rmgGate1, [this, minDist, &path2, &rmgGate1, &zShift, guarded2, &managerOther, &rmgGate2 ](const int3 & tile)
  278. {
  279. auto ti = map.getTileInfo(tile);
  280. auto otherTi = map.getTileInfo(tile - zShift);
  281. float dist = ti.getNearestObjectDistance();
  282. float otherDist = otherTi.getNearestObjectDistance();
  283. if(dist < minDist || otherDist < minDist)
  284. return -1.f;
  285. rmg::Area toPlace(rmgGate1.getArea() + rmgGate1.getAccessibleArea());
  286. toPlace.translate(-zShift);
  287. path2 = managerOther.placeAndConnectObject(toPlace, rmgGate2, minDist, guarded2, true, ObjectManager::OptimizeType::NONE);
  288. return path2.valid() ? (dist * otherDist) : -1.f;
  289. }, guarded1, true, ObjectManager::OptimizeType::DISTANCE);
  290. if(path1.valid() && path2.valid())
  291. {
  292. zone.connectPath(path1);
  293. otherZone->connectPath(path2);
  294. manager.placeObject(rmgGate1, guarded1, true);
  295. managerOther.placeObject(rmgGate2, guarded2, true);
  296. assert(otherZone->getModificator<ConnectionsPlacer>());
  297. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  298. success = true;
  299. }
  300. }
  301. }
  302. //4. place monoliths/portals
  303. if(!success)
  304. {
  305. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, generator.getNextMonlithIndex());
  306. auto * teleport1 = factory->create();
  307. auto * teleport2 = factory->create();
  308. zone.getModificator<ObjectManager>()->addRequiredObject(teleport1, connection.getGuardStrength());
  309. otherZone->getModificator<ObjectManager>()->addRequiredObject(teleport2, connection.getGuardStrength());
  310. assert(otherZone->getModificator<ConnectionsPlacer>());
  311. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  312. success = true;
  313. }
  314. if(success)
  315. dCompleted.push_back(connection);
  316. }
  317. void ConnectionsPlacer::collectNeighbourZones()
  318. {
  319. auto border = zone.area().getBorderOutside();
  320. for(const auto & i : border)
  321. {
  322. if(!map.isOnMap(i))
  323. continue;
  324. auto zid = map.getZoneID(i);
  325. assert(zid != zone.getId());
  326. dNeighbourZones[zid].insert(i);
  327. }
  328. }
  329. void ConnectionsPlacer::createBorder()
  330. {
  331. rmg::Area borderArea(zone.getArea().getBorder());
  332. rmg::Area borderOutsideArea(zone.getArea().getBorderOutside());
  333. auto blockBorder = borderArea.getSubarea([this, &borderOutsideArea](const int3 & t)
  334. {
  335. auto tile = borderOutsideArea.nearest(t);
  336. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getType() != ETemplateZoneType::WATER;
  337. });
  338. //No border for wide connections
  339. for (auto& connection : zone.getConnections()) // We actually placed that connection already
  340. {
  341. auto otherZone = connection.getOtherZoneId(zone.getId());
  342. if (connection.getConnectionType() == EConnectionType::EConnectionType::WIDE)
  343. {
  344. auto sharedBorder = borderArea.getSubarea([this, otherZone, &borderOutsideArea](const int3 & t)
  345. {
  346. auto tile = borderOutsideArea.nearest(t);
  347. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getId() == otherZone;
  348. });
  349. blockBorder.subtract(sharedBorder);
  350. }
  351. };
  352. Zone::Lock lock(zone.areaMutex); //Protect from erasing same tiles again
  353. for(const auto & tile : blockBorder.getTilesVector())
  354. {
  355. if(map.isPossible(tile))
  356. {
  357. map.setOccupied(tile, ETileType::BLOCKED);
  358. zone.areaPossible().erase(tile);
  359. }
  360. map.foreachDirectNeighbour(tile, [this](int3 &nearbyPos)
  361. {
  362. if(map.isPossible(nearbyPos) && map.getZoneID(nearbyPos) == zone.getId())
  363. {
  364. map.setOccupied(nearbyPos, ETileType::BLOCKED);
  365. zone.areaPossible().erase(nearbyPos);
  366. }
  367. });
  368. }
  369. }
  370. VCMI_LIB_NAMESPACE_END