CZonePlacer.cpp 14 KB

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