CZonePlacer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 "../mapping/CMap.h"
  15. #include "CZoneGraphGenerator.h"
  16. class CRandomGenerator;
  17. CPlacedZone::CPlacedZone(const CRmgTemplateZone * zone)
  18. {
  19. }
  20. CZonePlacer::CZonePlacer(CMapGenerator * Gen) : gen(Gen)
  21. {
  22. }
  23. CZonePlacer::~CZonePlacer()
  24. {
  25. }
  26. int3 CZonePlacer::cords (const float3 f) const
  27. {
  28. return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z);
  29. }
  30. void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand)
  31. {
  32. logGlobal->infoStream() << "Starting zone placement";
  33. int width = mapGenOptions->getWidth();
  34. int height = mapGenOptions->getHeight();
  35. auto zones = gen->getZones();
  36. bool underground = mapGenOptions->getHasTwoLevels();
  37. //gravity-based algorithm
  38. const float gravityConstant = 4e-3;
  39. const float stiffnessConstant = 4e-3;
  40. float zoneScale = 1.0f / std::sqrt(zones.size()); //zones starts small and then inflate. placing more zones is more difficult
  41. const float inflateModifier = 1.02;
  42. /*
  43. let's assume we try to fit N circular zones with radius = size on a map
  44. formula: sum((prescaler*n)^2)*pi = WH
  45. prescaler = sqrt((WH)/(sum(n^2)*pi))
  46. */
  47. std::vector<std::pair<TRmgTemplateZoneId, CRmgTemplateZone*>> zonesVector (zones.begin(), zones.end());
  48. assert (zonesVector.size());
  49. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  50. TRmgTemplateZoneId firstZone = zones.begin()->first; //we want lowest ID here
  51. bool undergroundFlag = false;
  52. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  53. const float radius = 0.4f;
  54. const float pi2 = 6.28f;
  55. for (auto zone : zonesVector)
  56. {
  57. //even distribution for surface / underground zones. Surface zones always have priority.
  58. int level = 0;
  59. if (underground) //only then consider underground zones
  60. {
  61. if (zone.first == firstZone)
  62. {
  63. level = 0;
  64. }
  65. else
  66. {
  67. level = undergroundFlag;
  68. undergroundFlag = !undergroundFlag; //toggle underground on/off
  69. }
  70. }
  71. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  72. float randomAngle = rand->nextDouble(0, pi2);
  73. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  74. }
  75. //prescale zones
  76. std::vector<float> prescaler = { 0, 0 };
  77. for (int i = 0; i < 2; i++)
  78. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  79. float mapSize = sqrt (width * height);
  80. for (auto zone : zones)
  81. {
  82. zone.second->setSize (zone.second->getSize() * prescaler[zone.second->getCenter().z]);
  83. }
  84. //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back
  85. //remember best solution
  86. float bestTotalDistance = 1e10;
  87. float bestTotalOverlap = 1e10;
  88. //float bestRatio = 1e10;
  89. std::map<CRmgTemplateZone *, float3> bestSolution;
  90. const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected
  91. auto getDistance = [](float distance) -> float
  92. {
  93. return (distance ? distance * distance : 1e-6);
  94. };
  95. std::map <CRmgTemplateZone *, float3> forces;
  96. std::map <CRmgTemplateZone *, float> distances;
  97. std::map <CRmgTemplateZone *, float> overlaps;
  98. while (zoneScale < 1) //until zones reach their desired size and fill the map tightly
  99. {
  100. for (auto zone : zones)
  101. {
  102. float3 forceVector(0,0,0);
  103. float3 pos = zone.second->getCenter();
  104. float totalDistance = 0;
  105. //attract connected zones
  106. for (auto con : zone.second->getConnections())
  107. {
  108. auto otherZone = zones[con];
  109. float3 otherZoneCenter = otherZone->getCenter();
  110. float distance = pos.dist2d (otherZoneCenter);
  111. float minDistance = (zone.second->getSize() + otherZone->getSize())/mapSize * zoneScale; //scale down to (0,1) coordinates
  112. if (distance > minDistance)
  113. {
  114. //WARNING: compiler used to 'optimize' that line so it never actually worked
  115. forceVector += (((otherZoneCenter - pos)*(pos.z == otherZoneCenter.z ? (minDistance/distance) : 1)/ getDistance(distance))) * gravityConstant; //positive value
  116. totalDistance += (distance - minDistance);
  117. }
  118. }
  119. distances[zone.second] = totalDistance;
  120. float totalOverlap = 0;
  121. //separate overlaping zones
  122. for (auto otherZone : zones)
  123. {
  124. float3 otherZoneCenter = otherZone.second->getCenter();
  125. //zones on different levels don't push away
  126. if (zone == otherZone || pos.z != otherZoneCenter.z)
  127. continue;
  128. float distance = pos.dist2d (otherZoneCenter);
  129. float minDistance = (zone.second->getSize() + otherZone.second->getSize())/mapSize * zoneScale;
  130. if (distance < minDistance)
  131. {
  132. forceVector -= (((otherZoneCenter - pos)*(minDistance/(distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value
  133. totalOverlap += (minDistance - distance) / (zoneScale * zoneScale); //overlapping of small zones hurts us more
  134. }
  135. }
  136. //move zones away from boundaries
  137. //do not scale boundary distance - zones tend to get squashed
  138. float size = zone.second->getSize() / mapSize;
  139. auto pushAwayFromBoundary = [&forceVector, pos, &getDistance, size, stiffnessConstant, &totalOverlap](float x, float y)
  140. {
  141. float3 boundary = float3 (x, y, pos.z);
  142. float distance = pos.dist2d(boundary);
  143. totalOverlap += distance; //overlapping map boundaries is wrong as well
  144. forceVector -= (boundary - pos) * (size - distance) / getDistance(distance) * stiffnessConstant; //negative value
  145. };
  146. if (pos.x < size)
  147. {
  148. pushAwayFromBoundary(0, pos.y);
  149. }
  150. if (pos.x > 1-size)
  151. {
  152. pushAwayFromBoundary(1, pos.y);
  153. }
  154. if (pos.y < size)
  155. {
  156. pushAwayFromBoundary(pos.x, 0);
  157. }
  158. if (pos.y > 1-size)
  159. {
  160. pushAwayFromBoundary(pos.x, 1);
  161. }
  162. overlaps[zone.second] = totalOverlap;
  163. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  164. forces[zone.second] = forceVector;
  165. }
  166. //update positions
  167. for (auto zone : forces)
  168. {
  169. zone.first->setCenter (zone.first->getCenter() + zone.second);
  170. }
  171. //now perform drastic movement of zone that is completely not linked
  172. float maxRatio = 0;
  173. CRmgTemplateZone * misplacedZone = nullptr;
  174. float totalDistance = 0;
  175. float totalOverlap = 0;
  176. for (auto zone : distances) //find most misplaced zone
  177. {
  178. totalDistance += zone.second;
  179. float overlap = overlaps[zone.first];
  180. totalOverlap += overlap;
  181. float ratio = (zone.second + overlap) / forces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  182. if (ratio > maxRatio)
  183. {
  184. maxRatio = ratio;
  185. misplacedZone = zone.first;
  186. }
  187. }
  188. logGlobal->traceStream() << boost::format("Total distance between zones in this iteration: %2.4f, Total overlap: %2.4f, Worst misplacement/movement ratio: %3.2f") % totalDistance % totalOverlap % maxRatio;
  189. //save best solution before drastic jump
  190. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  191. {
  192. bestTotalDistance = totalDistance;
  193. bestTotalOverlap = totalOverlap;
  194. //if (maxRatio < bestRatio)
  195. //{
  196. // bestRatio = maxRatio;
  197. for (auto zone : zones)
  198. bestSolution[zone.second] = zone.second->getCenter();
  199. }
  200. if (maxRatio > maxDistanceMovementRatio)
  201. {
  202. CRmgTemplateZone * targetZone = nullptr;
  203. float3 ourCenter = misplacedZone->getCenter();
  204. if (totalDistance > totalOverlap)
  205. {
  206. //find most distant zone that should be attracted and move inside it
  207. float maxDistance = 0;
  208. for (auto con : misplacedZone->getConnections())
  209. {
  210. auto otherZone = zones[con];
  211. float distance = otherZone->getCenter().dist2dSQ(ourCenter);
  212. if (distance > maxDistance)
  213. {
  214. maxDistance = distance;
  215. targetZone = otherZone;
  216. }
  217. }
  218. float3 vec = targetZone->getCenter() - ourCenter;
  219. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) * zoneScale / mapSize;
  220. logGlobal->traceStream() << boost::format("Trying to move zone %d %s towards %d %s. Old distance %f") %
  221. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxDistance;
  222. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  223. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  224. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  225. }
  226. else
  227. {
  228. float maxOverlap = 0;
  229. for (auto otherZone : zones)
  230. {
  231. float3 otherZoneCenter = otherZone.second->getCenter();
  232. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  233. continue;
  234. float distance = otherZoneCenter.dist2dSQ(ourCenter);
  235. if (distance > maxOverlap)
  236. {
  237. maxOverlap = distance;
  238. targetZone = otherZone.second;
  239. }
  240. }
  241. float3 vec = ourCenter - targetZone->getCenter();
  242. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) * zoneScale / mapSize;
  243. logGlobal->traceStream() << boost::format("Trying to move zone %d %s away from %d %s. Old distance %f") %
  244. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxOverlap;
  245. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  246. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  247. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  248. }
  249. }
  250. zoneScale *= inflateModifier; //increase size of zones so they
  251. }
  252. logGlobal->traceStream() << boost::format("Best fitness reached: total distance %2.4f, total overlap %2.4f") % bestTotalDistance % bestTotalOverlap;
  253. for (auto zone : zones) //finalize zone positions
  254. {
  255. zone.second->setPos (cords (bestSolution[zone.second]));
  256. logGlobal->traceStream() << boost::format ("Placed zone %d at relative position %s and coordinates %s") % zone.first % zone.second->getCenter() % zone.second->getPos();
  257. }
  258. }
  259. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  260. {
  261. /*
  262. Matlab code
  263. dx = abs(A(1) - B(1)); %distance must be symmetric
  264. dy = abs(A(2) - B(2));
  265. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  266. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  267. */
  268. float dx = abs(A.x - B.x) * scaleX;
  269. float dy = abs(A.y - B.y) * scaleY;
  270. //Horner scheme
  271. return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618));
  272. }
  273. void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions)
  274. {
  275. logGlobal->infoStream() << "Starting zone colouring";
  276. auto width = mapGenOptions->getWidth();
  277. auto height = mapGenOptions->getHeight();
  278. //scale to Medium map to ensure smooth results
  279. scaleX = 72.f / width;
  280. scaleY = 72.f / height;
  281. auto zones = gen->getZones();
  282. typedef std::pair<CRmgTemplateZone *, float> Dpair;
  283. std::vector <Dpair> distances;
  284. distances.reserve(zones.size());
  285. //now place zones correctly and assign tiles to each zone
  286. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  287. {
  288. return lhs.second < rhs.second;
  289. };
  290. auto moveZoneToCenterOfMass = [](CRmgTemplateZone * zone) -> void
  291. {
  292. int3 total(0, 0, 0);
  293. auto tiles = zone->getTileInfo();
  294. for (auto tile : tiles)
  295. {
  296. total += tile;
  297. }
  298. int size = tiles.size();
  299. assert(size);
  300. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  301. };
  302. int levels = gen->map->twoLevel ? 2 : 1;
  303. /*
  304. 1. Create Voronoi diagram
  305. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  306. */
  307. for (int i = 0; i<width; i++)
  308. {
  309. for (int j = 0; j<height; j++)
  310. {
  311. for (int k = 0; k < levels; k++)
  312. {
  313. distances.clear();
  314. int3 pos(i, j, k);
  315. for (auto zone : zones)
  316. {
  317. if (zone.second->getPos().z == k)
  318. distances.push_back(std::make_pair(zone.second, pos.dist2dSQ(zone.second->getPos())));
  319. else
  320. distances.push_back(std::make_pair(zone.second, std::numeric_limits<float>::max()));
  321. }
  322. boost::sort(distances, compareByDistance);
  323. distances.front().first->addTile(pos); //closest tile belongs to zone
  324. }
  325. }
  326. }
  327. for (auto zone : zones)
  328. moveZoneToCenterOfMass(zone.second);
  329. //assign actual tiles to each zone using nonlinear norm for fine edges
  330. for (auto zone : zones)
  331. zone.second->clearTiles(); //now populate them again
  332. for (int i=0; i<width; i++)
  333. {
  334. for(int j=0; j<height; j++)
  335. {
  336. for (int k = 0; k < levels; k++)
  337. {
  338. distances.clear();
  339. int3 pos(i, j, k);
  340. for (auto zone : zones)
  341. {
  342. if (zone.second->getPos().z == k)
  343. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  344. else
  345. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  346. }
  347. boost::sort (distances, compareByDistance);
  348. distances.front().first->addTile(pos); //closest tile belongs to zone
  349. }
  350. }
  351. }
  352. //set position (town position) to center of mass of irregular zone
  353. for (auto zone : zones)
  354. {
  355. moveZoneToCenterOfMass(zone.second);
  356. //TODO: similiar for islands
  357. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  358. if (zone.second->getPos().z)
  359. {
  360. if (!CREATE_FULL_UNDERGROUND)
  361. zone.second->discardDistantTiles(gen, zone.second->getSize() + 1);
  362. //make sure that terrain inside zone is not a rock
  363. //FIXME: reorder actions?
  364. zone.second->paintZoneTerrain (gen, ETerrainType::SUBTERRANEAN);
  365. }
  366. }
  367. logGlobal->infoStream() << "Finished zone colouring";
  368. }