WaterProxy.cpp 12 KB

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