CZonePlacer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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)
  21. : width(0), height(0), scaleX(0), scaleY(0), mapSize(0), gravityConstant(0), stiffnessConstant(0),
  22. gen(Gen)
  23. {
  24. }
  25. CZonePlacer::~CZonePlacer()
  26. {
  27. }
  28. int3 CZonePlacer::cords (const float3 f) const
  29. {
  30. return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z);
  31. }
  32. float CZonePlacer::getDistance (float distance) const
  33. {
  34. return (distance ? distance * distance : 1e-6);
  35. }
  36. void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand)
  37. {
  38. logGlobal->info("Starting zone placement");
  39. width = mapGenOptions->getWidth();
  40. height = mapGenOptions->getHeight();
  41. auto zones = gen->getZones();
  42. bool underground = mapGenOptions->getHasTwoLevels();
  43. /*
  44. gravity-based algorithm
  45. let's assume we try to fit N circular zones with radius = size on a map
  46. */
  47. gravityConstant = 4e-3;
  48. stiffnessConstant = 4e-3;
  49. TZoneVector zonesVector(zones.begin(), zones.end());
  50. assert (zonesVector.size());
  51. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  52. //0. set zone sizes and surface / underground level
  53. prepareZones(zones, zonesVector, underground, rand);
  54. //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back
  55. //remember best solution
  56. float bestTotalDistance = 1e10;
  57. float bestTotalOverlap = 1e10;
  58. std::map<CRmgTemplateZone *, float3> bestSolution;
  59. TForceVector forces;
  60. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  61. TDistanceVector distances;
  62. TDistanceVector overlaps;
  63. const int MAX_ITERATIONS = 100;
  64. for (int i = 0; i < MAX_ITERATIONS; ++i) //until zones reach their desired size and fill the map tightly
  65. {
  66. //1. attract connected zones
  67. attractConnectedZones(zones, forces, distances);
  68. for (auto zone : forces)
  69. {
  70. zone.first->setCenter (zone.first->getCenter() + zone.second);
  71. totalForces[zone.first] = zone.second; //override
  72. }
  73. //2. separate overlapping zones
  74. separateOverlappingZones(zones, forces, overlaps);
  75. for (auto zone : forces)
  76. {
  77. zone.first->setCenter (zone.first->getCenter() + zone.second);
  78. totalForces[zone.first] += zone.second; //accumulate
  79. }
  80. //3. now perform drastic movement of zone that is completely not linked
  81. moveOneZone(zones, totalForces, distances, overlaps);
  82. //4. NOW after everything was moved, re-evaluate zone positions
  83. attractConnectedZones(zones, forces, distances);
  84. separateOverlappingZones(zones, forces, overlaps);
  85. float totalDistance = 0;
  86. float totalOverlap = 0;
  87. for (auto zone : distances) //find most misplaced zone
  88. {
  89. totalDistance += zone.second;
  90. float overlap = overlaps[zone.first];
  91. totalOverlap += overlap;
  92. }
  93. //check fitness function
  94. bool improvement = false;
  95. if (bestTotalDistance > 0 && bestTotalOverlap > 0)
  96. {
  97. if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
  98. improvement = true;
  99. }
  100. else
  101. {
  102. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  103. improvement = true;
  104. }
  105. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  106. //save best solution
  107. if (improvement)
  108. {
  109. bestTotalDistance = totalDistance;
  110. bestTotalOverlap = totalOverlap;
  111. for (auto zone : zones)
  112. bestSolution[zone.second] = zone.second->getCenter();
  113. }
  114. }
  115. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  116. for (auto zone : zones) //finalize zone positions
  117. {
  118. zone.second->setPos (cords (bestSolution[zone.second]));
  119. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  120. }
  121. }
  122. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  123. {
  124. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  125. const float radius = 0.4f;
  126. const float pi2 = 6.28f;
  127. int zonesOnLevel[2] = { 0, 0 };
  128. //even distribution for surface / underground zones. Surface zones always have priority.
  129. TZoneVector zonesToPlace;
  130. std::map<TRmgTemplateZoneId, int> levels;
  131. //first pass - determine fixed surface for zones
  132. for (auto zone : zonesVector)
  133. {
  134. if (!underground) //this step is ignored
  135. zonesToPlace.push_back(zone);
  136. else //place players depending on their factions
  137. {
  138. if (boost::optional<int> owner = zone.second->getOwner())
  139. {
  140. auto player = PlayerColor(*owner - 1);
  141. auto playerSettings = gen->mapGenOptions->getPlayersSettings();
  142. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  143. if (vstd::contains(playerSettings, player))
  144. faction = playerSettings[player].getStartingTown();
  145. else
  146. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  147. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  148. zonesToPlace.push_back(zone);
  149. else
  150. {
  151. switch (VLC->townh->factions[faction]->nativeTerrain)
  152. {
  153. case ETerrainType::GRASS:
  154. case ETerrainType::SWAMP:
  155. case ETerrainType::SNOW:
  156. case ETerrainType::SAND:
  157. case ETerrainType::ROUGH:
  158. //surface
  159. zonesOnLevel[0]++;
  160. levels[zone.first] = 0;
  161. break;
  162. case ETerrainType::LAVA:
  163. case ETerrainType::SUBTERRANEAN:
  164. //underground
  165. zonesOnLevel[1]++;
  166. levels[zone.first] = 1;
  167. break;
  168. case ETerrainType::DIRT:
  169. default:
  170. //any / random
  171. zonesToPlace.push_back(zone);
  172. break;
  173. }
  174. }
  175. }
  176. else //no starting zone or no underground altogether
  177. {
  178. zonesToPlace.push_back(zone);
  179. }
  180. }
  181. }
  182. for (auto zone : zonesToPlace)
  183. {
  184. if (underground) //only then consider underground zones
  185. {
  186. int level = 0;
  187. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  188. level = 1;
  189. else
  190. level = 0;
  191. levels[zone.first] = level;
  192. zonesOnLevel[level]++;
  193. }
  194. else
  195. levels[zone.first] = 0;
  196. }
  197. for (auto zone : zonesVector)
  198. {
  199. int level = levels[zone.first];
  200. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  201. float randomAngle = rand->nextDouble(0, pi2);
  202. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  203. }
  204. /*
  205. prescale zones
  206. formula: sum((prescaler*n)^2)*pi = WH
  207. prescaler = sqrt((WH)/(sum(n^2)*pi))
  208. */
  209. std::vector<float> prescaler = { 0, 0 };
  210. for (int i = 0; i < 2; i++)
  211. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  212. mapSize = sqrt(width * height);
  213. for (auto zone : zones)
  214. {
  215. zone.second->setSize(zone.second->getSize() * prescaler[zone.second->getCenter().z]);
  216. }
  217. }
  218. void CZonePlacer::attractConnectedZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &distances)
  219. {
  220. for (auto zone : zones)
  221. {
  222. float3 forceVector(0, 0, 0);
  223. float3 pos = zone.second->getCenter();
  224. float totalDistance = 0;
  225. for (auto con : zone.second->getConnections())
  226. {
  227. auto otherZone = zones[con];
  228. float3 otherZoneCenter = otherZone->getCenter();
  229. float distance = pos.dist2d(otherZoneCenter);
  230. float minDistance = 0;
  231. if (pos.z != otherZoneCenter.z)
  232. minDistance = 0; //zones on different levels can overlap completely
  233. else
  234. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  235. if (distance > minDistance)
  236. {
  237. //WARNING: compiler used to 'optimize' that line so it never actually worked
  238. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  239. forceVector += (((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance))) * gravityConstant; //positive value
  240. totalDistance += (distance - minDistance);
  241. }
  242. }
  243. distances[zone.second] = totalDistance;
  244. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  245. forces[zone.second] = forceVector;
  246. }
  247. }
  248. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  249. {
  250. for (auto zone : zones)
  251. {
  252. float3 forceVector(0, 0, 0);
  253. float3 pos = zone.second->getCenter();
  254. float overlap = 0;
  255. //separate overlaping zones
  256. for (auto otherZone : zones)
  257. {
  258. float3 otherZoneCenter = otherZone.second->getCenter();
  259. //zones on different levels don't push away
  260. if (zone == otherZone || pos.z != otherZoneCenter.z)
  261. continue;
  262. float distance = pos.dist2d(otherZoneCenter);
  263. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  264. if (distance < minDistance)
  265. {
  266. forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value
  267. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  268. }
  269. }
  270. //move zones away from boundaries
  271. //do not scale boundary distance - zones tend to get squashed
  272. float size = zone.second->getSize() / mapSize;
  273. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  274. {
  275. float3 boundary = float3(x, y, pos.z);
  276. float distance = pos.dist2d(boundary);
  277. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  278. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
  279. };
  280. if (pos.x < size)
  281. {
  282. pushAwayFromBoundary(0, pos.y);
  283. }
  284. if (pos.x > 1 - size)
  285. {
  286. pushAwayFromBoundary(1, pos.y);
  287. }
  288. if (pos.y < size)
  289. {
  290. pushAwayFromBoundary(pos.x, 0);
  291. }
  292. if (pos.y > 1 - size)
  293. {
  294. pushAwayFromBoundary(pos.x, 1);
  295. }
  296. overlaps[zone.second] = overlap;
  297. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  298. forces[zone.second] = forceVector;
  299. }
  300. }
  301. void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDistanceVector &distances, TDistanceVector &overlaps)
  302. {
  303. float maxRatio = 0;
  304. const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected
  305. CRmgTemplateZone * misplacedZone = nullptr;
  306. float totalDistance = 0;
  307. float totalOverlap = 0;
  308. for (auto zone : distances) //find most misplaced zone
  309. {
  310. totalDistance += zone.second;
  311. float overlap = overlaps[zone.first];
  312. totalOverlap += overlap;
  313. float ratio = (zone.second + overlap) / totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  314. if (ratio > maxRatio)
  315. {
  316. maxRatio = ratio;
  317. misplacedZone = zone.first;
  318. }
  319. }
  320. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", maxRatio);
  321. if (maxRatio > maxDistanceMovementRatio && misplacedZone)
  322. {
  323. CRmgTemplateZone * targetZone = nullptr;
  324. float3 ourCenter = misplacedZone->getCenter();
  325. if (totalDistance > totalOverlap)
  326. {
  327. //find most distant zone that should be attracted and move inside it
  328. float maxDistance = 0;
  329. for (auto con : misplacedZone->getConnections())
  330. {
  331. auto otherZone = zones[con];
  332. float distance = otherZone->getCenter().dist2dSQ(ourCenter);
  333. if (distance > maxDistance)
  334. {
  335. maxDistance = distance;
  336. targetZone = otherZone;
  337. }
  338. }
  339. if (targetZone) //TODO: consider refactoring duplicated code
  340. {
  341. float3 vec = targetZone->getCenter() - ourCenter;
  342. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  343. logGlobal->trace("Trying to move zone %d %s towards %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxDistance);
  344. logGlobal->trace("direction is %s", vec.toString());
  345. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  346. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  347. }
  348. }
  349. else
  350. {
  351. float maxOverlap = 0;
  352. for (auto otherZone : zones)
  353. {
  354. float3 otherZoneCenter = otherZone.second->getCenter();
  355. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  356. continue;
  357. float distance = otherZoneCenter.dist2dSQ(ourCenter);
  358. if (distance > maxOverlap)
  359. {
  360. maxOverlap = distance;
  361. targetZone = otherZone.second;
  362. }
  363. }
  364. if (targetZone)
  365. {
  366. float3 vec = ourCenter - targetZone->getCenter();
  367. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  368. logGlobal->trace("Trying to move zone %d %s away from %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxOverlap);
  369. logGlobal->trace("direction is %s", vec.toString());
  370. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  371. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  372. }
  373. }
  374. }
  375. }
  376. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  377. {
  378. /*
  379. Matlab code
  380. dx = abs(A(1) - B(1)); %distance must be symmetric
  381. dy = abs(A(2) - B(2));
  382. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  383. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  384. */
  385. float dx = abs(A.x - B.x) * scaleX;
  386. float dy = abs(A.y - B.y) * scaleY;
  387. //Horner scheme
  388. return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618));
  389. }
  390. void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions)
  391. {
  392. logGlobal->info("Starting zone colouring");
  393. auto width = mapGenOptions->getWidth();
  394. auto height = mapGenOptions->getHeight();
  395. //scale to Medium map to ensure smooth results
  396. scaleX = 72.f / width;
  397. scaleY = 72.f / height;
  398. auto zones = gen->getZones();
  399. typedef std::pair<CRmgTemplateZone *, float> Dpair;
  400. std::vector <Dpair> distances;
  401. distances.reserve(zones.size());
  402. //now place zones correctly and assign tiles to each zone
  403. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  404. {
  405. //bigger zones have smaller distance
  406. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  407. };
  408. auto moveZoneToCenterOfMass = [](CRmgTemplateZone * zone) -> void
  409. {
  410. int3 total(0, 0, 0);
  411. auto tiles = zone->getTileInfo();
  412. for (auto tile : tiles)
  413. {
  414. total += tile;
  415. }
  416. int size = tiles.size();
  417. assert(size);
  418. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  419. };
  420. int levels = gen->map->twoLevel ? 2 : 1;
  421. /*
  422. 1. Create Voronoi diagram
  423. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  424. */
  425. for (int i = 0; i<width; i++)
  426. {
  427. for (int j = 0; j<height; j++)
  428. {
  429. for (int k = 0; k < levels; k++)
  430. {
  431. distances.clear();
  432. int3 pos(i, j, k);
  433. for (auto zone : zones)
  434. {
  435. if (zone.second->getPos().z == k)
  436. distances.push_back(std::make_pair(zone.second, pos.dist2dSQ(zone.second->getPos())));
  437. else
  438. distances.push_back(std::make_pair(zone.second, std::numeric_limits<float>::max()));
  439. }
  440. boost::min_element(distances, compareByDistance)->first->addTile(pos); //closest tile belongs to zone
  441. }
  442. }
  443. }
  444. for (auto zone : zones)
  445. moveZoneToCenterOfMass(zone.second);
  446. //assign actual tiles to each zone using nonlinear norm for fine edges
  447. for (auto zone : zones)
  448. zone.second->clearTiles(); //now populate them again
  449. for (int i=0; i<width; i++)
  450. {
  451. for(int j=0; j<height; j++)
  452. {
  453. for (int k = 0; k < levels; k++)
  454. {
  455. distances.clear();
  456. int3 pos(i, j, k);
  457. for (auto zone : zones)
  458. {
  459. if (zone.second->getPos().z == k)
  460. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  461. else
  462. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  463. }
  464. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  465. zone->addTile(pos);
  466. gen->setZoneID(pos, zone->getId());
  467. }
  468. }
  469. }
  470. //set position (town position) to center of mass of irregular zone
  471. for (auto zone : zones)
  472. {
  473. moveZoneToCenterOfMass(zone.second);
  474. //TODO: similiar for islands
  475. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  476. if (zone.second->getPos().z)
  477. {
  478. if (!CREATE_FULL_UNDERGROUND)
  479. zone.second->discardDistantTiles(gen, zone.second->getSize() + 1);
  480. //make sure that terrain inside zone is not a rock
  481. //FIXME: reorder actions?
  482. zone.second->paintZoneTerrain (gen, ETerrainType::SUBTERRANEAN);
  483. }
  484. }
  485. logGlobal->info("Finished zone colouring");
  486. }