ConnectionsPlacer.cpp 14 KB

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