Zone.cpp 10.0 KB

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