ConnectionsPlacer.cpp 16 KB

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