ConnectionsPlacer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 "../../mapObjects/CGCreature.h"
  18. #include "../../mapping/CMapEditManager.h"
  19. #include "../RmgObject.h"
  20. #include "ObjectManager.h"
  21. #include "../Functions.h"
  22. #include "RoadPlacer.h"
  23. #include "../TileInfo.h"
  24. #include "WaterAdopter.h"
  25. #include "WaterProxy.h"
  26. #include "TownPlacer.h"
  27. #include <boost/interprocess/sync/scoped_lock.hpp>
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. void ConnectionsPlacer::process()
  30. {
  31. collectNeighbourZones();
  32. auto diningPhilosophers = [this](std::function<void(const rmg::ZoneConnection&)> f)
  33. {
  34. for (auto& c : dConnections)
  35. {
  36. if (c.getZoneA() != zone.getId() && c.getZoneB() != zone.getId())
  37. continue;
  38. auto otherZone = map.getZones().at(c.getZoneB());
  39. auto* cp = otherZone->getModificator<ConnectionsPlacer>();
  40. while (cp)
  41. {
  42. RecursiveLock lock1(externalAccessMutex, boost::try_to_lock_t{});
  43. RecursiveLock lock2(cp->externalAccessMutex, boost::try_to_lock_t{});
  44. if (lock1.owns_lock() && lock2.owns_lock())
  45. {
  46. if (!vstd::contains(dCompleted, c))
  47. {
  48. f(c);
  49. }
  50. break;
  51. }
  52. }
  53. }
  54. };
  55. diningPhilosophers([this](const rmg::ZoneConnection& c)
  56. {
  57. selfSideDirectConnection(c);
  58. });
  59. createBorder();
  60. diningPhilosophers([this](const rmg::ZoneConnection& c)
  61. {
  62. selfSideIndirectConnection(c);
  63. });
  64. }
  65. void ConnectionsPlacer::init()
  66. {
  67. DEPENDENCY(WaterAdopter);
  68. DEPENDENCY(TownPlacer);
  69. POSTFUNCTION(RoadPlacer);
  70. POSTFUNCTION(ObjectManager);
  71. for(auto c : map.getMapGenOptions().getMapTemplate()->getConnectedZoneIds())
  72. addConnection(c);
  73. }
  74. void ConnectionsPlacer::addConnection(const rmg::ZoneConnection& connection)
  75. {
  76. dConnections.push_back(connection);
  77. }
  78. void ConnectionsPlacer::otherSideConnection(const rmg::ZoneConnection & connection)
  79. {
  80. dCompleted.push_back(connection);
  81. }
  82. void ConnectionsPlacer::selfSideDirectConnection(const rmg::ZoneConnection & connection)
  83. {
  84. bool success = false;
  85. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  86. auto & otherZone = map.getZones().at(otherZoneId);
  87. //1. Try to make direct connection
  88. //Do if it's not prohibited by terrain settings
  89. const auto * ourTerrain = VLC->terrainTypeHandler->getById(zone.getTerrainType());
  90. const auto * otherTerrain = VLC->terrainTypeHandler->getById(otherZone->getTerrainType());
  91. bool directProhibited = vstd::contains(ourTerrain->prohibitTransitions, otherZone->getTerrainType())
  92. || vstd::contains(otherTerrain->prohibitTransitions, zone.getTerrainType());
  93. auto directConnectionIterator = dNeighbourZones.find(otherZoneId);
  94. if (directConnectionIterator != dNeighbourZones.end())
  95. {
  96. if (connection.getConnectionType() == rmg::EConnectionType::WIDE)
  97. {
  98. for (auto borderPos : directConnectionIterator->second)
  99. {
  100. //TODO: Refactor common code with direct connection
  101. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  102. assert(borderPos != potentialPos);
  103. auto safetyGap = rmg::Area({ potentialPos });
  104. safetyGap.unite(safetyGap.getBorderOutside());
  105. safetyGap.intersect(zone.areaPossible());
  106. if (!safetyGap.empty())
  107. {
  108. safetyGap.intersect(otherZone->areaPossible());
  109. if (safetyGap.empty())
  110. {
  111. rmg::Area border(zone.getArea().getBorder());
  112. border.unite(otherZone->getArea().getBorder());
  113. auto costFunction = [&border](const int3& s, const int3& d)
  114. {
  115. return 1.f / (1.f + border.distanceSqr(d));
  116. };
  117. auto ourArea = zone.areaPossible() + zone.freePaths();
  118. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  119. theirArea.add(potentialPos);
  120. rmg::Path ourPath(ourArea);
  121. rmg::Path theirPath(theirArea);
  122. ourPath.connect(zone.freePaths());
  123. ourPath = ourPath.search(potentialPos, true, costFunction);
  124. theirPath.connect(otherZone->freePaths());
  125. theirPath = theirPath.search(potentialPos, true, costFunction);
  126. if (ourPath.valid() && theirPath.valid())
  127. {
  128. zone.connectPath(ourPath);
  129. otherZone->connectPath(theirPath);
  130. otherZone->getModificator<ObjectManager>()->updateDistances(potentialPos);
  131. success = true;
  132. break;
  133. }
  134. }
  135. }
  136. }
  137. }
  138. }
  139. if (connection.getConnectionType() == rmg::EConnectionType::FICTIVE ||
  140. connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  141. {
  142. //Fictive or repulsive connections are not real, take no action
  143. dCompleted.push_back(connection);
  144. return;
  145. }
  146. float maxDist = -10e6;
  147. if(!success && !directProhibited && directConnectionIterator != dNeighbourZones.end())
  148. {
  149. int3 guardPos(-1, -1, -1);
  150. int3 roadNode;
  151. for (auto borderPos : directConnectionIterator->second)
  152. {
  153. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  154. assert(borderPos != potentialPos);
  155. //Take into account distance to objects from both sides
  156. float dist = std::min(map.getTileInfo(potentialPos).getNearestObjectDistance(),
  157. map.getTileInfo(borderPos).getNearestObjectDistance());
  158. if (dist > 3) //Don't place guards at adjacent tiles
  159. {
  160. auto safetyGap = rmg::Area({ potentialPos });
  161. safetyGap.unite(safetyGap.getBorderOutside());
  162. safetyGap.intersect(zone.areaPossible());
  163. if (!safetyGap.empty())
  164. {
  165. safetyGap.intersect(otherZone->areaPossible());
  166. if (safetyGap.empty())
  167. {
  168. float distanceToCenter = zone.getPos().dist2d(potentialPos) * otherZone->getPos().dist2d(potentialPos);
  169. auto localDist = (dist - distanceToCenter) * //Prefer close to zone center
  170. (std::max(distanceToCenter, dist) / std::min(distanceToCenter, dist));
  171. //Distance to center dominates and is negative, so imbalanced proportions will result in huge penalty
  172. if (localDist > maxDist)
  173. {
  174. maxDist = localDist;
  175. guardPos = potentialPos;
  176. roadNode = borderPos;
  177. }
  178. }
  179. }
  180. }
  181. }
  182. if(guardPos.valid())
  183. {
  184. assert(zone.getModificator<ObjectManager>());
  185. auto & manager = *zone.getModificator<ObjectManager>();
  186. auto * monsterType = manager.chooseGuard(connection.getGuardStrength(), true);
  187. rmg::Area border(zone.getArea().getBorder());
  188. border.unite(otherZone->getArea().getBorder());
  189. auto costFunction = [&border](const int3 & s, const int3 & d)
  190. {
  191. return 1.f / (1.f + border.distanceSqr(d));
  192. };
  193. auto ourArea = zone.areaPossible() + zone.freePaths();
  194. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  195. theirArea.add(guardPos);
  196. rmg::Path ourPath(ourArea);
  197. rmg::Path theirPath(theirArea);
  198. ourPath.connect(zone.freePaths());
  199. ourPath = ourPath.search(guardPos, true, costFunction);
  200. theirPath.connect(otherZone->freePaths());
  201. theirPath = theirPath.search(guardPos, true, costFunction);
  202. if(ourPath.valid() && theirPath.valid())
  203. {
  204. zone.connectPath(ourPath);
  205. otherZone->connectPath(theirPath);
  206. if(monsterType)
  207. {
  208. rmg::Object monster(*monsterType);
  209. monster.setPosition(guardPos);
  210. manager.placeObject(monster, false, true, true);
  211. //Place objects away from the monster in the other zone, too
  212. otherZone->getModificator<ObjectManager>()->updateDistances(monster);
  213. }
  214. else
  215. {
  216. //Update distances from empty passage, too
  217. zone.areaPossible().erase(guardPos);
  218. zone.freePaths().add(guardPos);
  219. map.setOccupied(guardPos, ETileType::FREE);
  220. manager.updateDistances(guardPos);
  221. otherZone->getModificator<ObjectManager>()->updateDistances(guardPos);
  222. }
  223. if (shouldGenerateRoad(connection))
  224. {
  225. assert(zone.getModificator<RoadPlacer>());
  226. zone.getModificator<RoadPlacer>()->addRoadNode(guardPos);
  227. assert(otherZone->getModificator<RoadPlacer>());
  228. otherZone->getModificator<RoadPlacer>()->addRoadNode(roadNode);
  229. assert(otherZone->getModificator<ConnectionsPlacer>());
  230. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  231. }
  232. success = true;
  233. }
  234. }
  235. }
  236. //2. connect via water
  237. bool waterMode = map.getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  238. if(waterMode && zone.isUnderground() == otherZone->isUnderground())
  239. {
  240. if(generator.getZoneWater() && generator.getZoneWater()->getModificator<WaterProxy>())
  241. {
  242. if(generator.getZoneWater()->getModificator<WaterProxy>()->waterKeepConnection(connection.getZoneA(), connection.getZoneB()))
  243. {
  244. assert(otherZone->getModificator<ConnectionsPlacer>());
  245. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  246. success = true;
  247. }
  248. }
  249. }
  250. if(success)
  251. dCompleted.push_back(connection);
  252. }
  253. void ConnectionsPlacer::selfSideIndirectConnection(const rmg::ZoneConnection & connection)
  254. {
  255. bool success = false;
  256. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  257. auto & otherZone = map.getZones().at(otherZoneId);
  258. bool allowRoad = shouldGenerateRoad(connection);
  259. //3. place subterrain gates
  260. if(zone.isUnderground() != otherZone->isUnderground())
  261. {
  262. int3 zShift(0, 0, zone.getPos().z - otherZone->getPos().z);
  263. auto commonArea = zone.areaPossible() * (otherZone->areaPossible() + zShift);
  264. if(!commonArea.empty())
  265. {
  266. assert(zone.getModificator<ObjectManager>());
  267. auto & manager = *zone.getModificator<ObjectManager>();
  268. assert(otherZone->getModificator<ObjectManager>());
  269. auto & managerOther = *otherZone->getModificator<ObjectManager>();
  270. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  271. auto * gate1 = factory->create();
  272. auto * gate2 = factory->create();
  273. rmg::Object rmgGate1(*gate1);
  274. rmg::Object rmgGate2(*gate2);
  275. rmgGate1.setTemplate(zone.getTerrainType());
  276. rmgGate2.setTemplate(otherZone->getTerrainType());
  277. bool guarded1 = manager.addGuard(rmgGate1, connection.getGuardStrength(), true);
  278. bool guarded2 = managerOther.addGuard(rmgGate2, connection.getGuardStrength(), true);
  279. int minDist = 3;
  280. std::scoped_lock doubleLock(zone.areaMutex, otherZone->areaMutex);
  281. rmg::Path path2(otherZone->area());
  282. rmg::Path path1 = manager.placeAndConnectObject(commonArea, rmgGate1, [this, minDist, &path2, &rmgGate1, &zShift, guarded2, &managerOther, &rmgGate2 ](const int3 & tile)
  283. {
  284. auto ti = map.getTileInfo(tile);
  285. auto otherTi = map.getTileInfo(tile - zShift);
  286. float dist = ti.getNearestObjectDistance();
  287. float otherDist = otherTi.getNearestObjectDistance();
  288. if(dist < minDist || otherDist < minDist)
  289. return -1.f;
  290. rmg::Area toPlace(rmgGate1.getArea() + rmgGate1.getAccessibleArea());
  291. toPlace.translate(-zShift);
  292. path2 = managerOther.placeAndConnectObject(toPlace, rmgGate2, minDist, guarded2, true, ObjectManager::OptimizeType::NONE);
  293. return path2.valid() ? (dist * otherDist) : -1.f;
  294. }, guarded1, true, ObjectManager::OptimizeType::DISTANCE);
  295. if(path1.valid() && path2.valid())
  296. {
  297. zone.connectPath(path1);
  298. otherZone->connectPath(path2);
  299. manager.placeObject(rmgGate1, guarded1, true, allowRoad);
  300. managerOther.placeObject(rmgGate2, guarded2, true, allowRoad);
  301. assert(otherZone->getModificator<ConnectionsPlacer>());
  302. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  303. success = true;
  304. }
  305. }
  306. }
  307. //4. place monoliths/portals
  308. if(!success)
  309. {
  310. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, generator.getNextMonlithIndex());
  311. auto * teleport1 = factory->create();
  312. auto * teleport2 = factory->create();
  313. RequiredObjectInfo obj1(teleport1, connection.getGuardStrength(), allowRoad);
  314. RequiredObjectInfo obj2(teleport2, connection.getGuardStrength(), allowRoad);
  315. zone.getModificator<ObjectManager>()->addRequiredObject(obj1);
  316. otherZone->getModificator<ObjectManager>()->addRequiredObject(obj2);
  317. assert(otherZone->getModificator<ConnectionsPlacer>());
  318. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  319. success = true;
  320. }
  321. if(success)
  322. dCompleted.push_back(connection);
  323. }
  324. void ConnectionsPlacer::collectNeighbourZones()
  325. {
  326. auto border = zone.area().getBorderOutside();
  327. for(const auto & i : border)
  328. {
  329. if(!map.isOnMap(i))
  330. continue;
  331. auto zid = map.getZoneID(i);
  332. assert(zid != zone.getId());
  333. dNeighbourZones[zid].insert(i);
  334. }
  335. }
  336. bool ConnectionsPlacer::shouldGenerateRoad(const rmg::ZoneConnection& connection) const
  337. {
  338. return connection.getRoadOption() == rmg::ERoadOption::ROAD_TRUE ||
  339. (connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM && zone.getRand().nextDouble() >= 0.5f);
  340. }
  341. void ConnectionsPlacer::createBorder()
  342. {
  343. rmg::Area borderArea(zone.getArea().getBorder());
  344. rmg::Area borderOutsideArea(zone.getArea().getBorderOutside());
  345. auto blockBorder = borderArea.getSubarea([this, &borderOutsideArea](const int3 & t)
  346. {
  347. auto tile = borderOutsideArea.nearest(t);
  348. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getType() != ETemplateZoneType::WATER;
  349. });
  350. //No border for wide connections
  351. for (auto& connection : zone.getConnections()) // We actually placed that connection already
  352. {
  353. auto otherZone = connection.getOtherZoneId(zone.getId());
  354. if (connection.getConnectionType() == rmg::EConnectionType::WIDE)
  355. {
  356. auto sharedBorder = borderArea.getSubarea([this, otherZone, &borderOutsideArea](const int3 & t)
  357. {
  358. auto tile = borderOutsideArea.nearest(t);
  359. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getId() == otherZone;
  360. });
  361. blockBorder.subtract(sharedBorder);
  362. }
  363. };
  364. Zone::Lock lock(zone.areaMutex); //Protect from erasing same tiles again
  365. for(const auto & tile : blockBorder.getTilesVector())
  366. {
  367. if(map.isPossible(tile))
  368. {
  369. map.setOccupied(tile, ETileType::BLOCKED);
  370. zone.areaPossible().erase(tile);
  371. }
  372. map.foreachDirectNeighbour(tile, [this](int3 &nearbyPos)
  373. {
  374. if(map.isPossible(nearbyPos) && map.getZoneID(nearbyPos) == zone.getId())
  375. {
  376. map.setOccupied(nearbyPos, ETileType::BLOCKED);
  377. zone.areaPossible().erase(nearbyPos);
  378. }
  379. });
  380. }
  381. }
  382. VCMI_LIB_NAMESPACE_END