ConnectionsPlacer.cpp 15 KB

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