2
0

Zone.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * Zone.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 "Zone.h"
  12. #include "RmgMap.h"
  13. #include "Functions.h"
  14. #include "TileInfo.h"
  15. #include "CMapGenerator.h"
  16. #include "RmgPath.h"
  17. #include "modificators/ObjectManager.h"
  18. #include "../CRandomGenerator.h"
  19. #include <vstd/RNG.h>
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. const std::function<bool(const int3 &)> AREA_NO_FILTER = [](const int3 & t)
  22. {
  23. return true;
  24. };
  25. Zone::Zone(RmgMap & map, CMapGenerator & generator, vstd::RNG & r)
  26. : finished(false)
  27. , townType(ETownType::NEUTRAL)
  28. , terrainType(ETerrainId::GRASS)
  29. , map(map)
  30. , rand(std::make_unique<CRandomGenerator>(r.nextInt()))
  31. , generator(generator)
  32. {
  33. }
  34. Zone::~Zone() = default;
  35. bool Zone::isUnderground() const
  36. {
  37. return getPos().z == 1; // TODO: multilevel support
  38. }
  39. void Zone::setOptions(const ZoneOptions& options)
  40. {
  41. ZoneOptions::operator=(options);
  42. }
  43. float3 Zone::getCenter() const
  44. {
  45. return center;
  46. }
  47. void Zone::setCenter(const float3 &f)
  48. {
  49. //limit boundaries to (0,1) square
  50. //alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side
  51. center = f;
  52. center.x = static_cast<float>(std::fmod(center.x, 1));
  53. center.y = static_cast<float>(std::fmod(center.y, 1));
  54. if(center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive
  55. center.x = 1 - std::abs(center.x);
  56. if(center.y < 0)
  57. center.y = 1 - std::abs(center.y);
  58. }
  59. int3 Zone::getPos() const
  60. {
  61. return pos;
  62. }
  63. void Zone::setPos(const int3 &Pos)
  64. {
  65. pos = Pos;
  66. }
  67. ThreadSafeProxy<rmg::Area> Zone::area()
  68. {
  69. return ThreadSafeProxy<rmg::Area>(dArea, areaMutex);
  70. }
  71. ThreadSafeProxy<const rmg::Area> Zone::area() const
  72. {
  73. return ThreadSafeProxy<const rmg::Area>(dArea, areaMutex);
  74. }
  75. ThreadSafeProxy<rmg::Area> Zone::areaPossible()
  76. {
  77. return ThreadSafeProxy<rmg::Area>(dAreaPossible, areaMutex);
  78. }
  79. ThreadSafeProxy<const rmg::Area> Zone::areaPossible() const
  80. {
  81. return ThreadSafeProxy<const rmg::Area>(dAreaPossible, areaMutex);
  82. }
  83. ThreadSafeProxy<rmg::Area> Zone::freePaths()
  84. {
  85. return ThreadSafeProxy<rmg::Area>(dAreaFree, areaMutex);
  86. }
  87. ThreadSafeProxy<const rmg::Area> Zone::freePaths() const
  88. {
  89. return ThreadSafeProxy<const rmg::Area>(dAreaFree, areaMutex);
  90. }
  91. ThreadSafeProxy<rmg::Area> Zone::areaUsed()
  92. {
  93. return ThreadSafeProxy<rmg::Area>(dAreaUsed, areaMutex);
  94. }
  95. ThreadSafeProxy<const rmg::Area> Zone::areaUsed() const
  96. {
  97. return ThreadSafeProxy<const rmg::Area>(dAreaUsed, areaMutex);
  98. }
  99. rmg::Area Zone::areaForRoads() const
  100. {
  101. return areaPossible() + freePaths();
  102. }
  103. void Zone::clearTiles()
  104. {
  105. Lock lock(areaMutex);
  106. dArea.clear();
  107. dAreaPossible.clear();
  108. dAreaFree.clear();
  109. }
  110. void Zone::initFreeTiles()
  111. {
  112. rmg::Tileset possibleTiles;
  113. vstd::copy_if(dArea.getTiles(), vstd::set_inserter(possibleTiles), [this](const int3 &tile) -> bool
  114. {
  115. return map.isPossible(tile);
  116. });
  117. dAreaPossible.assign(possibleTiles);
  118. if(dAreaFree.empty() && getType() != ETemplateZoneType::SEALED)
  119. {
  120. // Fixme: This might fail fot water zone, which doesn't need to have a tile in its center of the mass
  121. dAreaPossible.erase(pos);
  122. dAreaFree.add(pos); //zone must have at least one free tile where other paths go - for instance in the center
  123. }
  124. }
  125. FactionID Zone::getTownType() const
  126. {
  127. return townType;
  128. }
  129. void Zone::setTownType(FactionID town)
  130. {
  131. townType = town;
  132. }
  133. TerrainId Zone::getTerrainType() const
  134. {
  135. return terrainType;
  136. }
  137. void Zone::setTerrainType(TerrainId terrain)
  138. {
  139. terrainType = terrain;
  140. }
  141. void Zone::moveToCenterOfMass()
  142. {
  143. auto newPos = area()->getCenterOfMass();
  144. setPos(newPos);
  145. setCenter(float3(float(newPos.x) / map.getMapGenOptions().getWidth(),
  146. float(newPos.y) / map.getMapGenOptions().getHeight(),
  147. newPos.z));
  148. }
  149. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  150. ///connect current tile to any other free tile within zone
  151. {
  152. auto movementCost = [this](const int3 & s, const int3 & d)
  153. {
  154. if(map.isFree(d))
  155. return 1;
  156. else if (map.isPossible(d))
  157. return 2;
  158. return 3;
  159. };
  160. auto area = (dAreaPossible + dAreaFree).getSubarea(areafilter);
  161. rmg::Path freePath(area);
  162. rmg::Path resultPath(area);
  163. freePath.connect(dAreaFree);
  164. //connect to all pieces
  165. auto goals = connectedAreas(src, onlyStraight);
  166. for(auto & goal : goals)
  167. {
  168. auto path = freePath.search(goal, onlyStraight, movementCost);
  169. if(path.getPathArea().empty())
  170. return rmg::Path::invalid();
  171. freePath.connect(path.getPathArea());
  172. resultPath.connect(path.getPathArea());
  173. }
  174. return resultPath;
  175. }
  176. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const rmg::Area & searchArea) const
  177. ///connect current tile to any other free tile within searchArea
  178. {
  179. auto movementCost = [this](const int3 & s, const int3 & d)
  180. {
  181. if(map.isFree(d))
  182. return 1;
  183. else if (map.isPossible(d))
  184. return 2;
  185. return 3;
  186. };
  187. rmg::Path freePath(searchArea);
  188. rmg::Path resultPath(searchArea);
  189. freePath.connect(dAreaFree);
  190. //connect to all pieces
  191. auto goals = connectedAreas(src, onlyStraight);
  192. for(auto & goal : goals)
  193. {
  194. auto path = freePath.search(goal, onlyStraight, movementCost);
  195. if(path.getPathArea().empty())
  196. return rmg::Path::invalid();
  197. freePath.connect(path.getPathArea());
  198. resultPath.connect(path.getPathArea());
  199. }
  200. return resultPath;
  201. }
  202. rmg::Path Zone::searchPath(const int3 & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  203. ///connect current tile to any other free tile within zone
  204. {
  205. return searchPath(rmg::Area({ src }), onlyStraight, areafilter);
  206. }
  207. TModificators Zone::getModificators()
  208. {
  209. return modificators;
  210. }
  211. void Zone::connectPath(const rmg::Path & path)
  212. ///connect current tile to any other free tile within zone
  213. {
  214. areaPossible()->subtract(path.getPathArea());
  215. freePaths()->unite(path.getPathArea());
  216. for(const auto & t : path.getPathArea().getTilesVector())
  217. map.setOccupied(t, ETileType::FREE);
  218. }
  219. void Zone::fractalize()
  220. {
  221. //Squared
  222. float minDistance = 9 * 9;
  223. float freeDistance = pos.z ? (10 * 10) : (9 * 9);
  224. float spanFactor = (pos.z ? 0.3f : 0.45f); //Narrower passages in the Underground
  225. float marginFactor = 1.0f;
  226. int treasureValue = 0;
  227. int treasureDensity = 0;
  228. for (const auto & t : treasureInfo)
  229. {
  230. treasureValue += ((t.min + t.max) / 2) * t.density / 1000.f; //Thousands
  231. treasureDensity += t.density;
  232. }
  233. if (getType() == ETemplateZoneType::WATER)
  234. {
  235. // Set very little obstacles on water
  236. spanFactor = 0.2;
  237. }
  238. else //Scale with treasure density
  239. {
  240. if (treasureValue > 250)
  241. {
  242. // A quarter at max density - means more free space
  243. marginFactor = (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  244. // Low value - dense obstacles
  245. spanFactor *= (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  246. }
  247. else if (treasureValue < 100)
  248. {
  249. //Dense obstacles
  250. spanFactor *= (0.5 + 0.5 * (treasureValue / 100.f));
  251. vstd::amax(spanFactor, 0.15f);
  252. }
  253. if (treasureDensity <= 10)
  254. {
  255. vstd::amin(spanFactor, 0.1f + 0.01f * treasureDensity); //Add extra obstacles to fill up space
  256. }
  257. }
  258. float blockDistance = minDistance * spanFactor; //More obstacles in the Underground
  259. freeDistance = freeDistance * marginFactor;
  260. vstd::amax(freeDistance, 4 * 4);
  261. logGlobal->trace("Zone %d: treasureValue %d blockDistance: %2.f, freeDistance: %2.f", getId(), treasureValue, blockDistance, freeDistance);
  262. Lock lock(areaMutex);
  263. rmg::Area clearedTiles(dAreaFree);
  264. rmg::Area possibleTiles(dAreaPossible);
  265. rmg::Area tilesToIgnore; //will be erased in this iteration
  266. if(type != ETemplateZoneType::JUNCTION)
  267. {
  268. //junction is not fractalized, has only one straight path
  269. //everything else remains blocked
  270. while(!possibleTiles.empty())
  271. {
  272. //link tiles in random order
  273. std::vector<int3> tilesToMakePath = possibleTiles.getTilesVector();
  274. // Do not fractalize tiles near the edge of the map to avoid paths adjacent to map edge
  275. const auto h = map.height();
  276. const auto w = map.width();
  277. const size_t MARGIN = 3;
  278. vstd::erase_if(tilesToMakePath, [&, h, w](const int3 & tile)
  279. {
  280. return tile.x < MARGIN || tile.x > (w - MARGIN) ||
  281. tile.y < MARGIN || tile.y > (h - MARGIN);
  282. });
  283. RandomGeneratorUtil::randomShuffle(tilesToMakePath, getRand());
  284. int3 nodeFound(-1, -1, -1);
  285. for(const auto & tileToMakePath : tilesToMakePath)
  286. {
  287. //find closest free tile
  288. int3 closestTile = clearedTiles.nearest(tileToMakePath);
  289. if(closestTile.dist2dSQ(tileToMakePath) <= freeDistance)
  290. tilesToIgnore.add(tileToMakePath);
  291. else
  292. {
  293. //if tiles are not close enough, make path to it
  294. nodeFound = tileToMakePath;
  295. clearedTiles.add(nodeFound); //from now on nearby tiles will be considered handled
  296. break; //next iteration - use already cleared tiles
  297. }
  298. }
  299. possibleTiles.subtract(tilesToIgnore);
  300. if(!nodeFound.isValid()) //nothing else can be done (?)
  301. break;
  302. tilesToIgnore.clear();
  303. }
  304. }
  305. else if (type == ETemplateZoneType::SEALED)
  306. {
  307. //Completely block all the tiles in the zone
  308. auto tiles = areaPossible()->getTiles();
  309. for(const auto & t : tiles)
  310. map.setOccupied(t, ETileType::BLOCKED);
  311. possibleTiles.clear();
  312. dAreaFree.clear();
  313. return;
  314. }
  315. else
  316. {
  317. // Handle special case - place Monoliths at the edge of a zone
  318. auto objectManager = getModificator<ObjectManager>();
  319. if (objectManager)
  320. {
  321. objectManager->createMonoliths();
  322. }
  323. }
  324. //Connect with free areas
  325. auto areas = connectedAreas(clearedTiles, true);
  326. for(auto & area : areas)
  327. {
  328. if(dAreaFree.overlap(area))
  329. continue; //already found
  330. auto availableArea = dAreaPossible + dAreaFree;
  331. rmg::Path path(availableArea);
  332. path.connect(dAreaFree);
  333. auto res = path.search(area, true);
  334. if(res.getPathArea().empty())
  335. {
  336. dAreaPossible.subtract(area);
  337. dAreaFree.subtract(area);
  338. for(const auto & t : area.getTiles())
  339. map.setOccupied(t, ETileType::BLOCKED);
  340. }
  341. else
  342. {
  343. dAreaPossible.subtract(res.getPathArea());
  344. dAreaFree.unite(res.getPathArea());
  345. for(const auto & t : res.getPathArea().getTiles())
  346. map.setOccupied(t, ETileType::FREE);
  347. }
  348. }
  349. //now block most distant tiles away from passages
  350. auto areaToBlock = dArea.getSubarea([this, blockDistance](const int3 & t)
  351. {
  352. auto distance = static_cast<float>(dAreaFree.distanceSqr(t));
  353. return distance > blockDistance;
  354. });
  355. dAreaPossible.subtract(areaToBlock);
  356. dAreaFree.subtract(areaToBlock);
  357. lock.unlock();
  358. for(const auto & t : areaToBlock.getTiles())
  359. map.setOccupied(t, ETileType::BLOCKED);
  360. }
  361. void Zone::initModificators()
  362. {
  363. for(auto & modificator : modificators)
  364. {
  365. modificator->init();
  366. }
  367. }
  368. vstd::RNG& Zone::getRand()
  369. {
  370. return *rand;
  371. }
  372. VCMI_LIB_NAMESPACE_END