CZonePlacer.cpp 18 KB

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