CZonePlacer.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. * CZonePlacer.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 "../CRandomGenerator.h"
  12. #include "CZonePlacer.h"
  13. #include "CRmgTemplateZone.h"
  14. #include "CZoneGraphGenerator.h"
  15. class CRandomGenerator;
  16. CPlacedZone::CPlacedZone(const CRmgTemplateZone * zone)
  17. {
  18. }
  19. CZonePlacer::CZonePlacer(CMapGenerator * Gen) : gen(Gen)
  20. {
  21. }
  22. CZonePlacer::~CZonePlacer()
  23. {
  24. }
  25. int3 CZonePlacer::cords (const float3 f) const
  26. {
  27. return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z);
  28. }
  29. void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand)
  30. {
  31. //gravity-based algorithm
  32. float gravityConstant = 1e-2;
  33. float zoneScale = 0.5f; //zones starts small and then inflate
  34. const float inflateModifier = 1.02;
  35. logGlobal->infoStream() << "Starting zone placement";
  36. int width = mapGenOptions->getWidth();
  37. int height = mapGenOptions->getHeight();
  38. auto zones = gen->getZones();
  39. bool underground = mapGenOptions->getHasTwoLevels();
  40. /*
  41. let's assume we try to fit N circular zones with radius = size on a map
  42. formula: sum((prescaler*n)^2)*pi = WH
  43. prescaler = sqrt((WH)/(sum(n^2)*pi))
  44. */
  45. std::vector<std::pair<TRmgTemplateZoneId, CRmgTemplateZone*>> zonesVector (zones.begin(), zones.end());
  46. assert (zonesVector.size());
  47. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  48. TRmgTemplateZoneId firstZone = zones.begin()->first; //we want lowest ID here
  49. bool undergroundFlag = false;
  50. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  51. for (auto zone : zonesVector)
  52. {
  53. //even distribution for surface / underground zones. Surface zones always have priority.
  54. int level = 0;
  55. if (underground) //only then consider underground zones
  56. {
  57. if (zone.first == firstZone)
  58. {
  59. level = 0;
  60. }
  61. else
  62. {
  63. level = undergroundFlag;
  64. undergroundFlag = !undergroundFlag; //toggle underground on/off
  65. }
  66. }
  67. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  68. zone.second->setCenter (float3(rand->nextDouble(0.2, 0.8), rand->nextDouble(0.2, 0.8), level)); //start away from borders
  69. }
  70. //prescale zones
  71. std::vector<float> prescaler = { 0, 0 };
  72. for (int i = 0; i < 2; i++)
  73. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  74. float mapSize = sqrt (width * height);
  75. for (auto zone : zones)
  76. {
  77. zone.second->setSize (zone.second->getSize() * prescaler[zone.second->getCenter().z]);
  78. }
  79. //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back
  80. auto getDistance = [](float distance) -> float
  81. {
  82. return (distance ? distance * distance : 1e-6);
  83. };
  84. std::map <CRmgTemplateZone *, float3> forces;
  85. std::map <CRmgTemplateZone *, float> distances;
  86. while (zoneScale < 1) //until zones reach their desired size and fill the map tightly
  87. {
  88. for (auto zone : zones)
  89. {
  90. float3 forceVector(0,0,0);
  91. float3 pos = zone.second->getCenter();
  92. float totalDistance = 0;
  93. //attract connected zones
  94. for (auto con : zone.second->getConnections())
  95. {
  96. auto otherZone = zones[con];
  97. float3 otherZoneCenter = otherZone->getCenter();
  98. float distance = pos.dist2d (otherZoneCenter);
  99. float minDistance = (zone.second->getSize() + otherZone->getSize())/mapSize * zoneScale; //scale down to (0,1) coordinates
  100. if (distance > minDistance)
  101. {
  102. //WARNING: compiler used to 'optimize' that line so it never actually worked
  103. forceVector += (((otherZoneCenter - pos)*(pos.z != otherZoneCenter.z ? (distance - minDistance) : 1)/ getDistance(distance))); //positive value
  104. totalDistance += distance;
  105. }
  106. }
  107. distances[zone.second] = totalDistance;
  108. //separate overlaping zones
  109. for (auto otherZone : zones)
  110. {
  111. float3 otherZoneCenter = otherZone.second->getCenter();
  112. //zones on different levels don't push away
  113. if (zone == otherZone || pos.z != otherZoneCenter.z)
  114. continue;
  115. float distance = pos.dist2d (otherZoneCenter);
  116. float minDistance = (zone.second->getSize() + otherZone.second->getSize())/mapSize * zoneScale;
  117. if (distance < minDistance)
  118. {
  119. forceVector -= (((otherZoneCenter - pos)*(minDistance - distance)) / getDistance(distance)); //negative value
  120. }
  121. }
  122. //move zones away from boundaries
  123. //do not scale boundary distance - zones tend to get squashed
  124. float size = zone.second->getSize() / mapSize;
  125. auto pushAwayFromBoundary = [&forceVector, pos, &getDistance](float x, float y)
  126. {
  127. float3 boundary = float3 (x, y, pos.z);
  128. float distance = pos.dist2d(boundary);
  129. forceVector -= (boundary - pos) / getDistance(distance); //negative value
  130. };
  131. if (pos.x < size)
  132. {
  133. pushAwayFromBoundary(0, pos.y);
  134. }
  135. if (pos.x > 1-size)
  136. {
  137. pushAwayFromBoundary(1, pos.y);
  138. }
  139. if (pos.y < size)
  140. {
  141. pushAwayFromBoundary(pos.x, 0);
  142. }
  143. if (pos.y > 1-size)
  144. {
  145. pushAwayFromBoundary(pos.x, 1);
  146. }
  147. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  148. forces[zone.second] = forceVector * gravityConstant;
  149. }
  150. //update positions
  151. for (auto zone : forces)
  152. {
  153. zone.first->setCenter (zone.first->getCenter() + zone.second);
  154. }
  155. //now perform drastic movement of zone that is completely not linked
  156. float maxRatio = 0;
  157. CRmgTemplateZone * distantZone = nullptr;
  158. float totalDistance = 0;
  159. for (auto zone : distances) //find most misplaced zone
  160. {
  161. totalDistance += zone.second;
  162. float ratio = zone.second / forces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  163. if (ratio > maxRatio)
  164. {
  165. maxRatio = ratio;
  166. distantZone = zone.first;
  167. }
  168. }
  169. logGlobal->traceStream() << boost::format("Total distance between zones in this iteration: %2.2f, Worst distance/movement ratio: %3.2f") % totalDistance % maxRatio;
  170. if (maxRatio > 100) //TODO: scale?
  171. {
  172. //find most distant zone that should be attracted and move inside it
  173. CRmgTemplateZone * targetZone = nullptr;
  174. float maxDistance = 0;
  175. float3 ourCenter = distantZone->getCenter();
  176. for (auto con : distantZone->getConnections())
  177. {
  178. auto otherZone = zones[con];
  179. float distance = otherZone->getCenter().dist2dSQ(ourCenter);
  180. if (distance > maxDistance)
  181. {
  182. maxDistance = distance;
  183. targetZone = otherZone;
  184. }
  185. }
  186. float3 vec = targetZone->getCenter() - ourCenter;
  187. float newDistanceBetweenZones = (std::max (distantZone->getSize(),targetZone->getSize())) * zoneScale / mapSize;
  188. logGlobal->traceStream() << boost::format("Trying to move zone %d %s towards %d %s. Old distance %f") %
  189. distantZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxDistance;
  190. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  191. distantZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  192. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(distantZone->getCenter());
  193. }
  194. zoneScale *= inflateModifier; //increase size of zones so they
  195. }
  196. for (auto zone : zones) //finalize zone positions
  197. {
  198. zone.second->setPos(cords(zone.second->getCenter()));
  199. logGlobal->infoStream() << boost::format ("Placed zone %d at relative position %s and coordinates %s") % zone.first % zone.second->getCenter() % zone.second->getPos();
  200. }
  201. }
  202. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  203. {
  204. /*
  205. Matlab code
  206. dx = abs(A(1) - B(1)); %distance must be symmetric
  207. dy = abs(A(2) - B(2));
  208. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  209. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  210. */
  211. float dx = abs(A.x - B.x) * scaleX;
  212. float dy = abs(A.y - B.y) * scaleY;
  213. //Horner scheme
  214. return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618));
  215. }
  216. void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions)
  217. {
  218. logGlobal->infoStream() << "Starting zone colouring";
  219. auto width = mapGenOptions->getWidth();
  220. auto height = mapGenOptions->getHeight();
  221. //scale to Medium map to ensure smooth results
  222. scaleX = 72.f / width;
  223. scaleY = 72.f / height;
  224. auto zones = gen->getZones();
  225. typedef std::pair<CRmgTemplateZone *, float> Dpair;
  226. std::vector <Dpair> distances;
  227. distances.reserve(zones.size());
  228. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  229. {
  230. return lhs.second < rhs.second;
  231. };
  232. int levels = gen->map->twoLevel ? 2 : 1;
  233. for (int i=0; i<width; i++)
  234. {
  235. for(int j=0; j<height; j++)
  236. {
  237. for (int k = 0; k < levels; k++)
  238. {
  239. distances.clear();
  240. int3 pos(i, j, k);
  241. for (auto zone : zones)
  242. {
  243. if (zone.second->getPos().z == k)
  244. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  245. else
  246. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  247. }
  248. boost::sort (distances, compareByDistance);
  249. distances.front().first->addTile(pos); //closest tile belongs to zone
  250. }
  251. }
  252. }
  253. //set position to center of mass
  254. for (auto zone : zones)
  255. {
  256. int3 total(0,0,0);
  257. auto tiles = zone.second->getTileInfo();
  258. for (auto tile : tiles)
  259. {
  260. total += tile;
  261. }
  262. int size = tiles.size();
  263. assert (size);
  264. zone.second->setPos (int3(total.x/size, total.y/size, total.z/size));
  265. //TODO: similiar for islands
  266. if (zone.second->getPos().z)
  267. {
  268. zone.second->discardDistantTiles(gen, zone.second->getSize() + 1);
  269. //make sure that terrain inside zone is not a rock
  270. //FIXME: reorder actions?
  271. zone.second->paintZoneTerrain (gen, ETerrainType::SUBTERRANEAN);
  272. }
  273. }
  274. logGlobal->infoStream() << "Finished zone colouring";
  275. }