Zone.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 "../mapping/CMap.h"
  16. #include "../CStopWatch.h"
  17. #include "CMapGenerator.h"
  18. #include "RmgPath.h"
  19. std::function<bool(const int3 &)> AREA_NO_FILTER = [](const int3 & t)
  20. {
  21. return true;
  22. };
  23. Zone::Zone(RmgMap & map, CMapGenerator & generator)
  24. : ZoneOptions(),
  25. townType(ETownType::NEUTRAL),
  26. terrainType(Terrain::GRASS),
  27. map(map),
  28. generator(generator)
  29. {
  30. }
  31. bool Zone::isUnderground() const
  32. {
  33. return getPos().z;
  34. }
  35. void Zone::setOptions(const ZoneOptions& options)
  36. {
  37. ZoneOptions::operator=(options);
  38. }
  39. float3 Zone::getCenter() const
  40. {
  41. return center;
  42. }
  43. void Zone::setCenter(const float3 &f)
  44. {
  45. //limit boundaries to (0,1) square
  46. //alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side
  47. center = f;
  48. center.x = static_cast<float>(std::fmod(center.x, 1));
  49. center.y = static_cast<float>(std::fmod(center.y, 1));
  50. if(center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive
  51. center.x = 1 - std::abs(center.x);
  52. if(center.y < 0)
  53. center.y = 1 - std::abs(center.y);
  54. }
  55. int3 Zone::getPos() const
  56. {
  57. return pos;
  58. }
  59. void Zone::setPos(const int3 &Pos)
  60. {
  61. pos = Pos;
  62. }
  63. const rmg::Area & Zone::getArea() const
  64. {
  65. return dArea;
  66. }
  67. rmg::Area & Zone::area()
  68. {
  69. return dArea;
  70. }
  71. rmg::Area & Zone::areaPossible()
  72. {
  73. return dAreaPossible;
  74. }
  75. rmg::Area & Zone::areaUsed()
  76. {
  77. return dAreaUsed;
  78. }
  79. void Zone::clearTiles()
  80. {
  81. dArea.clear();
  82. dAreaPossible.clear();
  83. dAreaFree.clear();
  84. }
  85. void Zone::initFreeTiles()
  86. {
  87. rmg::Tileset possibleTiles;
  88. vstd::copy_if(dArea.getTiles(), vstd::set_inserter(possibleTiles), [this](const int3 &tile) -> bool
  89. {
  90. return map.isPossible(tile);
  91. });
  92. dAreaPossible.assign(possibleTiles);
  93. if(dAreaFree.empty())
  94. {
  95. dAreaPossible.erase(pos);
  96. dAreaFree.add(pos); //zone must have at least one free tile where other paths go - for instance in the center
  97. }
  98. }
  99. rmg::Area & Zone::freePaths()
  100. {
  101. return dAreaFree;
  102. }
  103. si32 Zone::getTownType() const
  104. {
  105. return townType;
  106. }
  107. void Zone::setTownType(si32 town)
  108. {
  109. townType = town;
  110. }
  111. TTerrainId Zone::getTerrainType() const
  112. {
  113. return terrainType;
  114. }
  115. void Zone::setTerrainType(TTerrainId terrain)
  116. {
  117. terrainType = terrain;
  118. }
  119. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, std::function<bool(const int3 &)> areafilter) const
  120. ///connect current tile to any other free tile within zone
  121. {
  122. auto movementCost = [this](const int3 & s, const int3 & d)
  123. {
  124. if(map.isFree(d))
  125. return 1;
  126. else if (map.isPossible(d))
  127. return 2;
  128. return 3;
  129. };
  130. auto area = (dAreaPossible + dAreaFree).getSubarea(areafilter);
  131. rmg::Path freePath(area), resultPath(area);
  132. freePath.connect(dAreaFree);
  133. //connect to all pieces
  134. auto goals = connectedAreas(src, onlyStraight);
  135. for(auto & goal : goals)
  136. {
  137. auto path = freePath.search(goal, onlyStraight, movementCost);
  138. if(path.getPathArea().empty())
  139. return rmg::Path::invalid();
  140. freePath.connect(path.getPathArea());
  141. resultPath.connect(path.getPathArea());
  142. }
  143. return resultPath;
  144. }
  145. rmg::Path Zone::searchPath(const int3 & src, bool onlyStraight, std::function<bool(const int3 &)> areafilter) const
  146. ///connect current tile to any other free tile within zone
  147. {
  148. return searchPath(rmg::Area({src}), onlyStraight, areafilter);
  149. }
  150. void Zone::connectPath(const rmg::Path & path)
  151. ///connect current tile to any other free tile within zone
  152. {
  153. dAreaPossible.subtract(path.getPathArea());
  154. dAreaFree.unite(path.getPathArea());
  155. for(auto & t : path.getPathArea().getTilesVector())
  156. map.setOccupied(t, ETileType::FREE);
  157. }
  158. void Zone::fractalize()
  159. {
  160. rmg::Area clearedTiles(dAreaFree);
  161. rmg::Area possibleTiles(dAreaPossible);
  162. rmg::Area tilesToIgnore; //will be erased in this iteration
  163. const float minDistance = 10 * 10; //squared
  164. if(type != ETemplateZoneType::JUNCTION)
  165. {
  166. //junction is not fractalized, has only one straight path
  167. //everything else remains blocked
  168. while(!possibleTiles.empty())
  169. {
  170. //link tiles in random order
  171. std::vector<int3> tilesToMakePath = possibleTiles.getTilesVector();
  172. RandomGeneratorUtil::randomShuffle(tilesToMakePath, generator.rand);
  173. int3 nodeFound(-1, -1, -1);
  174. for(auto tileToMakePath : tilesToMakePath)
  175. {
  176. //find closest free tile
  177. int3 closestTile = clearedTiles.nearest(tileToMakePath);
  178. if(closestTile.dist2dSQ(tileToMakePath) <= minDistance)
  179. tilesToIgnore.add(tileToMakePath);
  180. else
  181. {
  182. //if tiles are not close enough, make path to it
  183. nodeFound = tileToMakePath;
  184. clearedTiles.add(nodeFound); //from now on nearby tiles will be considered handled
  185. break; //next iteration - use already cleared tiles
  186. }
  187. }
  188. possibleTiles.subtract(tilesToIgnore);
  189. if(!nodeFound.valid()) //nothing else can be done (?)
  190. break;
  191. tilesToIgnore.clear();
  192. }
  193. }
  194. //cut straight paths towards the center. A* is too slow for that.
  195. auto areas = connectedAreas(clearedTiles, false);
  196. for(auto & area : areas)
  197. {
  198. if(dAreaFree.overlap(area))
  199. continue; //already found
  200. auto availableArea = dAreaPossible + dAreaFree;
  201. rmg::Path path(availableArea);
  202. path.connect(dAreaFree);
  203. auto res = path.search(area, false);
  204. if(res.getPathArea().empty())
  205. {
  206. dAreaPossible.subtract(area);
  207. dAreaFree.subtract(area);
  208. for(auto & t : area.getTiles())
  209. map.setOccupied(t, ETileType::BLOCKED);
  210. }
  211. else
  212. {
  213. dAreaPossible.subtract(res.getPathArea());
  214. dAreaFree.unite(res.getPathArea());
  215. for(auto & t : res.getPathArea().getTiles())
  216. map.setOccupied(t, ETileType::FREE);
  217. }
  218. }
  219. //now block most distant tiles away from passages
  220. float blockDistance = minDistance * 0.25f;
  221. auto areaToBlock = dArea.getSubarea([this, blockDistance](const int3 & t)
  222. {
  223. float distance = static_cast<float>(dAreaFree.distanceSqr(t));
  224. return distance > blockDistance;
  225. });
  226. dAreaPossible.subtract(areaToBlock);
  227. dAreaFree.subtract(areaToBlock);
  228. for(auto & t : areaToBlock.getTiles())
  229. map.setOccupied(t, ETileType::BLOCKED);
  230. }
  231. void Zone::initModificators()
  232. {
  233. for(auto & modificator : modificators)
  234. {
  235. modificator->init();
  236. }
  237. logGlobal->info("Zone %d modificators initialized", getId());
  238. }
  239. void Zone::processModificators()
  240. {
  241. for(auto & modificator : modificators)
  242. {
  243. try
  244. {
  245. modificator->run();
  246. }
  247. catch (const rmgException & e)
  248. {
  249. logGlobal->info("Zone %d, modificator %s - FAILED: %s", getId(), e.what());
  250. throw e;
  251. }
  252. }
  253. logGlobal->info("Zone %d filled successfully", getId());
  254. }
  255. Modificator::Modificator(Zone & zone, RmgMap & map, CMapGenerator & generator) : zone(zone), map(map), generator(generator)
  256. {
  257. }
  258. void Modificator::setName(const std::string & n)
  259. {
  260. name = n;
  261. }
  262. const std::string & Modificator::getName() const
  263. {
  264. return name;
  265. }
  266. bool Modificator::isFinished() const
  267. {
  268. return finished;
  269. }
  270. void Modificator::run()
  271. {
  272. started = true;
  273. if(!finished)
  274. {
  275. for(auto * modificator : preceeders)
  276. {
  277. if(!modificator->started)
  278. modificator->run();
  279. }
  280. logGlobal->info("Modificator zone %d - %s - started", zone.getId(), getName());
  281. CStopWatch processTime;
  282. try
  283. {
  284. process();
  285. }
  286. catch(rmgException &e)
  287. {
  288. logGlobal->error("Modificator %s, exception: %s", getName(), e.what());
  289. }
  290. #ifdef RMG_DUMP
  291. dump();
  292. #endif
  293. finished = true;
  294. logGlobal->info("Modificator zone %d - %s - done (%d ms)", zone.getId(), getName(), processTime.getDiff());
  295. }
  296. }
  297. void Modificator::dependency(Modificator * modificator)
  298. {
  299. if(modificator && modificator != this)
  300. {
  301. if(std::find(preceeders.begin(), preceeders.end(), modificator) == preceeders.end())
  302. preceeders.push_back(modificator);
  303. }
  304. }
  305. void Modificator::postfunction(Modificator * modificator)
  306. {
  307. if(modificator && modificator != this)
  308. {
  309. if(std::find(modificator->preceeders.begin(), modificator->preceeders.end(), this) == modificator->preceeders.end())
  310. modificator->preceeders.push_back(this);
  311. }
  312. }
  313. void Modificator::dump()
  314. {
  315. std::ofstream out(boost::to_string(boost::format("seed_%d_modzone_%d_%s.txt") % generator.getRandomSeed() % zone.getId() % getName()));
  316. auto & mapInstance = map.map();
  317. int levels = mapInstance.levels();
  318. int width = mapInstance.width;
  319. int height = mapInstance.height;
  320. for(int z = 0; z < levels; z++)
  321. {
  322. for(int j=0; j<height; j++)
  323. {
  324. for(int i=0; i<width; i++)
  325. {
  326. out << dump(int3(i, j, z));
  327. }
  328. out << std::endl;
  329. }
  330. out << std::endl;
  331. }
  332. out << std::endl;
  333. }
  334. char Modificator::dump(const int3 & t)
  335. {
  336. if(zone.freePaths().contains(t))
  337. return '.'; //free path
  338. if(zone.areaPossible().contains(t))
  339. return ' '; //possible
  340. if(zone.areaUsed().contains(t))
  341. return 'U'; //used
  342. if(zone.area().contains(t))
  343. {
  344. if(map.shouldBeBlocked(t))
  345. return '#'; //obstacle
  346. else
  347. return '^'; //visitable points?
  348. }
  349. return '?';
  350. }
  351. Modificator::~Modificator()
  352. {
  353. }