CZonePlacer.cpp 18 KB

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