WaterProxy.cpp 11 KB

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