WaterProxy.cpp 11 KB

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