ConnectionsPlacer.cpp 15 KB

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