WaterProxy.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /*
  2. * WaterProxy.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 "WaterProxy.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/MiscObjects.h"
  18. #include "../../mapping/CMap.h"
  19. #include "../../mapping/CMapEditManager.h"
  20. #include "../RmgPath.h"
  21. #include "../RmgObject.h"
  22. #include "ObjectManager.h"
  23. #include "../Functions.h"
  24. #include "RoadPlacer.h"
  25. #include "TreasurePlacer.h"
  26. #include "TownPlacer.h"
  27. #include "ConnectionsPlacer.h"
  28. #include "../TileInfo.h"
  29. #include "WaterAdopter.h"
  30. #include "../RmgArea.h"
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void WaterProxy::process()
  33. {
  34. auto area = zone.area();
  35. for(const auto & t : area->getTilesVector())
  36. {
  37. map.setZoneID(t, zone.getId());
  38. map.setOccupied(t, ETileType::POSSIBLE);
  39. }
  40. auto v = area->getTilesVector();
  41. mapProxy->drawTerrain(zone.getRand(), v, zone.getTerrainType());
  42. //check terrain type
  43. for([[maybe_unused]] const auto & t : area->getTilesVector())
  44. {
  45. assert(map.isOnMap(t));
  46. assert(map.getTile(t).terType->getId() == zone.getTerrainType());
  47. }
  48. // FIXME: Possible deadlock for 2 zones
  49. auto areaPossible = zone.areaPossible();
  50. for(const auto & z : map.getZones())
  51. {
  52. if(z.second->getId() == zone.getId())
  53. continue;
  54. auto secondArea = z.second->area();
  55. auto secondAreaPossible = z.second->areaPossible();
  56. for(const auto & t : secondArea->getTilesVector())
  57. {
  58. if(map.getTile(t).terType->getId() == zone.getTerrainType())
  59. {
  60. secondArea->erase(t);
  61. secondAreaPossible->erase(t);
  62. area->add(t);
  63. areaPossible->add(t);
  64. map.setZoneID(t, zone.getId());
  65. map.setOccupied(t, ETileType::POSSIBLE);
  66. }
  67. }
  68. }
  69. if(!area->contains(zone.getPos()))
  70. {
  71. zone.setPos(area->getTilesVector().front());
  72. }
  73. zone.initFreeTiles();
  74. collectLakes();
  75. }
  76. void WaterProxy::init()
  77. {
  78. for(auto & z : map.getZones())
  79. {
  80. if (!zone.isUnderground())
  81. {
  82. dependency(z.second->getModificator<TownPlacer>());
  83. dependency(z.second->getModificator<WaterAdopter>());
  84. }
  85. postfunction(z.second->getModificator<ConnectionsPlacer>());
  86. postfunction(z.second->getModificator<ObjectManager>());
  87. }
  88. POSTFUNCTION(TreasurePlacer);
  89. }
  90. const std::vector<WaterProxy::Lake> & WaterProxy::getLakes() const
  91. {
  92. RecursiveLock lock(externalAccessMutex);
  93. return lakes;
  94. }
  95. void WaterProxy::collectLakes()
  96. {
  97. RecursiveLock lock(externalAccessMutex);
  98. int lakeId = 0;
  99. for(const auto & lake : connectedAreas(zone.area().get(), true))
  100. {
  101. lakes.push_back(Lake{});
  102. lakes.back().area = lake;
  103. lakes.back().distanceMap = lake.computeDistanceMap(lakes.back().reverseDistanceMap);
  104. for(const auto & t : lake.getBorderOutside())
  105. if(map.isOnMap(t))
  106. lakes.back().neighbourZones[map.getZoneID(t)].add(t);
  107. for(const auto & t : lake.getTilesVector())
  108. lakeMap[t] = lakeId;
  109. //each lake must have at least one free tile
  110. if(!lake.overlap(zone.freePaths().get()))
  111. zone.freePaths()->add(*lakes.back().reverseDistanceMap[lakes.back().reverseDistanceMap.size() - 1].begin());
  112. ++lakeId;
  113. }
  114. }
  115. RouteInfo WaterProxy::waterRoute(Zone & dst)
  116. {
  117. RouteInfo result;
  118. auto * adopter = dst.getModificator<WaterAdopter>();
  119. if(!adopter)
  120. return result;
  121. if(adopter->getCoastTiles().empty())
  122. return result;
  123. bool createRoad = false;
  124. //block zones are not connected by template
  125. for(auto& lake : lakes)
  126. {
  127. if(lake.neighbourZones.count(dst.getId()))
  128. {
  129. if(!lake.keepConnections.count(dst.getId()))
  130. {
  131. for(const auto & ct : lake.neighbourZones[dst.getId()].getTilesVector())
  132. {
  133. if(map.isPossible(ct))
  134. map.setOccupied(ct, ETileType::BLOCKED);
  135. }
  136. Zone::Lock lock(dst.areaMutex);
  137. dst.areaPossible()->subtract(lake.neighbourZones[dst.getId()]);
  138. continue;
  139. }
  140. //Don't place shipyard or boats on the very small lake
  141. if (lake.area.getTilesVector().size() < 25)
  142. {
  143. logGlobal->info("Skipping very small lake at zone %d", dst.getId());
  144. continue;
  145. }
  146. int zoneTowns = 0;
  147. if(auto * m = dst.getModificator<TownPlacer>())
  148. zoneTowns = m->getTotalTowns();
  149. if (vstd::contains(lake.keepRoads, dst.getId()))
  150. {
  151. createRoad = true;
  152. }
  153. //FIXME: Why are Shipyards not allowed in zones with no towns?
  154. if(dst.getType() == ETemplateZoneType::PLAYER_START || dst.getType() == ETemplateZoneType::CPU_START || zoneTowns)
  155. {
  156. if(placeShipyard(dst, lake, generator.getConfig().shipyardGuard, createRoad, result))
  157. {
  158. logGlobal->info("Shipyard successfully placed at zone %d", dst.getId());
  159. }
  160. else
  161. {
  162. logGlobal->warn("Shipyard placement failed, trying boat at zone %d", dst.getId());
  163. if(placeBoat(dst, lake, createRoad, result))
  164. {
  165. logGlobal->warn("Boat successfully placed at zone %d", dst.getId());
  166. }
  167. else
  168. {
  169. logGlobal->error("Boat placement failed at zone %d", dst.getId());
  170. }
  171. }
  172. }
  173. else
  174. {
  175. if(placeBoat(dst, lake, createRoad, result))
  176. {
  177. logGlobal->info("Boat successfully placed at zone %d", dst.getId());
  178. }
  179. else
  180. {
  181. logGlobal->error("Boat placement failed at zone %d", dst.getId());
  182. }
  183. }
  184. }
  185. }
  186. return result;
  187. }
  188. bool WaterProxy::waterKeepConnection(const rmg::ZoneConnection & connection, bool createRoad)
  189. {
  190. const auto & zoneA = connection.getZoneA();
  191. const auto & zoneB = connection.getZoneB();
  192. for(auto & lake : lakes)
  193. {
  194. if(lake.neighbourZones.count(zoneA) && lake.neighbourZones.count(zoneB))
  195. {
  196. lake.keepConnections.insert(zoneA);
  197. lake.keepConnections.insert(zoneB);
  198. if (createRoad)
  199. {
  200. lake.keepRoads.insert(zoneA);
  201. lake.keepRoads.insert(zoneB);
  202. }
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. bool WaterProxy::placeBoat(Zone & land, const Lake & lake, bool createRoad, RouteInfo & info)
  209. {
  210. auto * manager = zone.getModificator<ObjectManager>();
  211. if(!manager)
  212. return false;
  213. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::BOAT);
  214. std::set<si32> sailingBoatTypes; //RMG shall place only sailing boats on water
  215. for(auto subObj : subObjects)
  216. {
  217. //making a temporary object
  218. std::unique_ptr<CGObjectInstance> obj(VLC->objtypeh->getHandlerFor(Obj::BOAT, subObj)->create(map.mapInstance->cb, nullptr));
  219. if(auto * testBoat = dynamic_cast<CGBoat *>(obj.get()))
  220. {
  221. if(testBoat->layer == EPathfindingLayer::SAIL)
  222. sailingBoatTypes.insert(subObj);
  223. }
  224. }
  225. if(sailingBoatTypes.empty())
  226. return false;
  227. auto * boat = dynamic_cast<CGBoat *>(VLC->objtypeh->getHandlerFor(Obj::BOAT, *RandomGeneratorUtil::nextItem(sailingBoatTypes, zone.getRand()))->create(map.mapInstance->cb, nullptr));
  228. rmg::Object rmgObject(*boat);
  229. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  230. auto waterAvailable = zone.areaPossible() + zone.freePaths();
  231. rmg::Area coast = lake.neighbourZones.at(land.getId()); //having land tiles
  232. coast.intersect(land.areaPossible() + land.freePaths()); //having only available land tiles
  233. auto boardingPositions = coast.getSubarea([&waterAvailable, this](const int3 & tile) //tiles where boarding is possible
  234. {
  235. //We don't want place boat right to any land object, especiallly the zone guard
  236. if (map.getTileInfo(tile).getNearestObjectDistance() <= 3)
  237. return false;
  238. rmg::Area a({tile});
  239. a = a.getBorderOutside();
  240. a.intersect(waterAvailable);
  241. return !a.empty();
  242. });
  243. while(!boardingPositions.empty())
  244. {
  245. auto boardingPosition = *boardingPositions.getTilesVector().begin();
  246. rmg::Area shipPositions({boardingPosition});
  247. auto boutside = shipPositions.getBorderOutside();
  248. shipPositions.assign(boutside);
  249. shipPositions.intersect(waterAvailable);
  250. if(shipPositions.empty())
  251. {
  252. boardingPositions.erase(boardingPosition);
  253. continue;
  254. }
  255. //try to place boat at water, create paths on water and land
  256. auto path = manager->placeAndConnectObject(shipPositions, rmgObject, 4, false, true, ObjectManager::OptimizeType::NONE);
  257. auto landPath = land.searchPath(boardingPosition, false);
  258. if(!path.valid() || !landPath.valid())
  259. {
  260. boardingPositions.erase(boardingPosition);
  261. continue;
  262. }
  263. info.blocked = rmgObject.getArea();
  264. info.visitable = rmgObject.getVisitablePosition();
  265. info.boarding = boardingPosition;
  266. info.water = shipPositions;
  267. zone.connectPath(path);
  268. land.connectPath(landPath);
  269. manager->placeObject(rmgObject, false, true, createRoad);
  270. land.getModificator<ObjectManager>()->updateDistances(rmgObject); //Keep land objects away from the boat
  271. break;
  272. }
  273. return !boardingPositions.empty();
  274. }
  275. bool WaterProxy::placeShipyard(Zone & land, const Lake & lake, si32 guard, bool createRoad, RouteInfo & info)
  276. {
  277. auto * manager = land.getModificator<ObjectManager>();
  278. if(!manager)
  279. return false;
  280. int subtype = chooseRandomAppearance(zone.getRand(), Obj::SHIPYARD, land.getTerrainType());
  281. auto * shipyard = dynamic_cast<CGShipyard *>(VLC->objtypeh->getHandlerFor(Obj::SHIPYARD, subtype)->create(map.mapInstance->cb, nullptr));
  282. shipyard->tempOwner = PlayerColor::NEUTRAL;
  283. rmg::Object rmgObject(*shipyard);
  284. rmgObject.setTemplate(land.getTerrainType(), zone.getRand());
  285. bool guarded = manager->addGuard(rmgObject, guard);
  286. auto waterAvailable = zone.areaPossible() + zone.freePaths();
  287. waterAvailable.intersect(lake.area);
  288. rmg::Area coast = lake.neighbourZones.at(land.getId()); //having land tiles
  289. coast.intersect(land.areaPossible() + land.freePaths()); //having only available land tiles
  290. auto boardingPositions = coast.getSubarea([&waterAvailable](const int3 & tile) //tiles where boarding is possible
  291. {
  292. rmg::Area a({tile});
  293. a = a.getBorderOutside();
  294. a.intersect(waterAvailable);
  295. return !a.empty();
  296. });
  297. while(!boardingPositions.empty())
  298. {
  299. auto boardingPosition = *boardingPositions.getTilesVector().begin();
  300. rmg::Area shipPositions({boardingPosition});
  301. auto boutside = shipPositions.getBorderOutside();
  302. shipPositions.assign(boutside);
  303. shipPositions.intersect(waterAvailable);
  304. if(shipPositions.empty())
  305. {
  306. boardingPositions.erase(boardingPosition);
  307. continue;
  308. }
  309. //try to place shipyard close to boarding position and appropriate water access
  310. auto path = manager->placeAndConnectObject(land.areaPossible().get(), rmgObject, [&rmgObject, &shipPositions, &boardingPosition](const int3 & tile)
  311. {
  312. //Must only check the border of shipyard and not the added guard
  313. rmg::Area shipyardOut = rmgObject.instances().front()->getBlockedArea().getBorderOutside();
  314. if(!shipyardOut.contains(boardingPosition) || (shipyardOut * shipPositions).empty())
  315. return -1.f;
  316. return 1.0f;
  317. }, guarded, true, ObjectManager::OptimizeType::NONE);
  318. //search path to boarding position
  319. auto searchArea = land.areaPossible().get() - rmgObject.getArea();
  320. rmg::Path pathToBoarding(searchArea);
  321. pathToBoarding.connect(land.freePaths().get());
  322. pathToBoarding.connect(path);
  323. pathToBoarding = pathToBoarding.search(boardingPosition, false);
  324. //make sure shipyard places ship at position we defined
  325. rmg::Area shipyardOutToBlock(rmgObject.getArea().getBorderOutside());
  326. shipyardOutToBlock.intersect(waterAvailable);
  327. shipyardOutToBlock.subtract(shipPositions);
  328. shipPositions.subtract(shipyardOutToBlock);
  329. auto pathToBoat = zone.searchPath(shipPositions, true);
  330. if(!path.valid() || !pathToBoarding.valid() || !pathToBoat.valid())
  331. {
  332. boardingPositions.erase(boardingPosition);
  333. continue;
  334. }
  335. land.connectPath(path);
  336. land.connectPath(pathToBoarding);
  337. zone.connectPath(pathToBoat);
  338. info.blocked = rmgObject.getArea();
  339. info.visitable = rmgObject.getVisitablePosition();
  340. info.boarding = boardingPosition;
  341. info.water = shipPositions;
  342. manager->placeObject(rmgObject, guarded, true, createRoad);
  343. zone.areaPossible()->subtract(shipyardOutToBlock);
  344. for(const auto & i : shipyardOutToBlock.getTilesVector())
  345. if(map.isOnMap(i) && map.isPossible(i))
  346. map.setOccupied(i, ETileType::BLOCKED);
  347. break;
  348. }
  349. return !boardingPositions.empty();
  350. }
  351. char WaterProxy::dump(const int3 & t)
  352. {
  353. auto lakeIter = lakeMap.find(t);
  354. if(lakeIter == lakeMap.end())
  355. return '?';
  356. Lake & lake = lakes[lakeMap.at(t)];
  357. for(const auto & i : lake.neighbourZones)
  358. {
  359. if(i.second.contains(t))
  360. return lake.keepConnections.count(i.first) ? std::to_string(i.first)[0] : '=';
  361. }
  362. return '~';
  363. }
  364. VCMI_LIB_NAMESPACE_END