ConnectionsPlacer.cpp 15 KB

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