CZonePlacer.cpp 17 KB

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