CZonePlacer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. const auto & terrainType = VLC->terrainTypeHandler->terrains()[tt];
  164. if(terrainType.isUnderground() && !terrainType.isSurface())
  165. {
  166. //underground only
  167. zonesOnLevel[1]++;
  168. levels[zone.first] = 1;
  169. }
  170. else
  171. {
  172. //surface
  173. zonesOnLevel[0]++;
  174. levels[zone.first] = 0;
  175. }
  176. }
  177. }
  178. }
  179. else //no starting zone or no underground altogether
  180. {
  181. zonesToPlace.push_back(zone);
  182. }
  183. }
  184. }
  185. for (auto zone : zonesToPlace)
  186. {
  187. if (underground) //only then consider underground zones
  188. {
  189. int level = 0;
  190. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  191. level = 1;
  192. else
  193. level = 0;
  194. levels[zone.first] = level;
  195. zonesOnLevel[level]++;
  196. }
  197. else
  198. levels[zone.first] = 0;
  199. }
  200. for (auto zone : zonesVector)
  201. {
  202. int level = levels[zone.first];
  203. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  204. float randomAngle = static_cast<float>(rand->nextDouble(0, pi2));
  205. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  206. }
  207. /*
  208. prescale zones
  209. formula: sum((prescaler*n)^2)*pi = WH
  210. prescaler = sqrt((WH)/(sum(n^2)*pi))
  211. */
  212. std::vector<float> prescaler = { 0, 0 };
  213. for (int i = 0; i < 2; i++)
  214. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  215. mapSize = static_cast<float>(sqrt(width * height));
  216. for (auto zone : zones)
  217. {
  218. zone.second->setSize((int)(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  219. }
  220. }
  221. void CZonePlacer::attractConnectedZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &distances)
  222. {
  223. for (auto zone : zones)
  224. {
  225. float3 forceVector(0, 0, 0);
  226. float3 pos = zone.second->getCenter();
  227. float totalDistance = 0;
  228. for (auto con : zone.second->getConnections())
  229. {
  230. auto otherZone = zones[con];
  231. float3 otherZoneCenter = otherZone->getCenter();
  232. float distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  233. float minDistance = 0;
  234. if (pos.z != otherZoneCenter.z)
  235. minDistance = 0; //zones on different levels can overlap completely
  236. else
  237. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  238. if (distance > minDistance)
  239. {
  240. //WARNING: compiler used to 'optimize' that line so it never actually worked
  241. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  242. forceVector += ((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance)) * gravityConstant; //positive value
  243. totalDistance += (distance - minDistance);
  244. }
  245. }
  246. distances[zone.second] = totalDistance;
  247. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  248. forces[zone.second] = forceVector;
  249. }
  250. }
  251. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  252. {
  253. for (auto zone : zones)
  254. {
  255. float3 forceVector(0, 0, 0);
  256. float3 pos = zone.second->getCenter();
  257. float overlap = 0;
  258. //separate overlapping zones
  259. for (auto otherZone : zones)
  260. {
  261. float3 otherZoneCenter = otherZone.second->getCenter();
  262. //zones on different levels don't push away
  263. if (zone == otherZone || pos.z != otherZoneCenter.z)
  264. continue;
  265. float distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  266. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  267. if (distance < minDistance)
  268. {
  269. forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stiffnessConstant; //negative value
  270. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  271. }
  272. }
  273. //move zones away from boundaries
  274. //do not scale boundary distance - zones tend to get squashed
  275. float size = zone.second->getSize() / mapSize;
  276. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  277. {
  278. float3 boundary = float3(x, y, pos.z);
  279. float distance = static_cast<float>(pos.dist2d(boundary));
  280. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  281. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
  282. };
  283. if (pos.x < size)
  284. {
  285. pushAwayFromBoundary(0, pos.y);
  286. }
  287. if (pos.x > 1 - size)
  288. {
  289. pushAwayFromBoundary(1, pos.y);
  290. }
  291. if (pos.y < size)
  292. {
  293. pushAwayFromBoundary(pos.x, 0);
  294. }
  295. if (pos.y > 1 - size)
  296. {
  297. pushAwayFromBoundary(pos.x, 1);
  298. }
  299. overlaps[zone.second] = overlap;
  300. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  301. forces[zone.second] = forceVector;
  302. }
  303. }
  304. void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDistanceVector &distances, TDistanceVector &overlaps)
  305. {
  306. float maxRatio = 0;
  307. const int maxDistanceMovementRatio = static_cast<int>(zones.size() * zones.size()); //experimental - the more zones, the greater total distance expected
  308. std::shared_ptr<Zone> misplacedZone;
  309. float totalDistance = 0;
  310. float totalOverlap = 0;
  311. for (auto zone : distances) //find most misplaced zone
  312. {
  313. totalDistance += zone.second;
  314. float overlap = overlaps[zone.first];
  315. totalOverlap += overlap;
  316. float ratio = (zone.second + overlap) / (float)totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  317. if (ratio > maxRatio)
  318. {
  319. maxRatio = ratio;
  320. misplacedZone = zone.first;
  321. }
  322. }
  323. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", maxRatio);
  324. if (maxRatio > maxDistanceMovementRatio && misplacedZone)
  325. {
  326. std::shared_ptr<Zone> targetZone;
  327. float3 ourCenter = misplacedZone->getCenter();
  328. if (totalDistance > totalOverlap)
  329. {
  330. //find most distant zone that should be attracted and move inside it
  331. float maxDistance = 0;
  332. for (auto con : misplacedZone->getConnections())
  333. {
  334. auto otherZone = zones[con];
  335. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  336. if (distance > maxDistance)
  337. {
  338. maxDistance = distance;
  339. targetZone = otherZone;
  340. }
  341. }
  342. if (targetZone) //TODO: consider refactoring duplicated code
  343. {
  344. float3 vec = targetZone->getCenter() - ourCenter;
  345. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  346. logGlobal->trace("Trying to move zone %d %s towards %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxDistance);
  347. logGlobal->trace("direction is %s", vec.toString());
  348. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  349. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  350. }
  351. }
  352. else
  353. {
  354. float maxOverlap = 0;
  355. for (auto otherZone : zones)
  356. {
  357. float3 otherZoneCenter = otherZone.second->getCenter();
  358. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  359. continue;
  360. float distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  361. if (distance > maxOverlap)
  362. {
  363. maxOverlap = distance;
  364. targetZone = otherZone.second;
  365. }
  366. }
  367. if (targetZone)
  368. {
  369. float3 vec = ourCenter - targetZone->getCenter();
  370. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  371. 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);
  372. logGlobal->trace("direction is %s", vec.toString());
  373. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  374. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  375. }
  376. }
  377. }
  378. }
  379. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  380. {
  381. /*
  382. Matlab code
  383. dx = abs(A(1) - B(1)); %distance must be symmetric
  384. dy = abs(A(2) - B(2));
  385. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  386. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  387. */
  388. float dx = abs(A.x - B.x) * scaleX;
  389. float dy = abs(A.y - B.y) * scaleY;
  390. //Horner scheme
  391. return dx * (1.0f + dx * (0.1f + dx * 0.01f)) + dy * (1.618f + dy * (-0.1618f + dy * 0.01618f));
  392. }
  393. void CZonePlacer::assignZones(CRandomGenerator * rand)
  394. {
  395. logGlobal->info("Starting zone colouring");
  396. auto width = map.getMapGenOptions().getWidth();
  397. auto height = map.getMapGenOptions().getHeight();
  398. //scale to Medium map to ensure smooth results
  399. scaleX = 72.f / width;
  400. scaleY = 72.f / height;
  401. auto zones = map.getZones();
  402. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  403. {
  404. return pr.second->getType() == ETemplateZoneType::WATER;
  405. });
  406. typedef std::pair<std::shared_ptr<Zone>, float> Dpair;
  407. std::vector <Dpair> distances;
  408. distances.reserve(zones.size());
  409. //now place zones correctly and assign tiles to each zone
  410. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  411. {
  412. //bigger zones have smaller distance
  413. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  414. };
  415. auto moveZoneToCenterOfMass = [](std::shared_ptr<Zone> zone) -> void
  416. {
  417. int3 total(0, 0, 0);
  418. auto tiles = zone->area().getTiles();
  419. for (auto tile : tiles)
  420. {
  421. total += tile;
  422. }
  423. int size = static_cast<int>(tiles.size());
  424. assert(size);
  425. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  426. };
  427. int levels = map.map().levels();
  428. /*
  429. 1. Create Voronoi diagram
  430. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  431. */
  432. int3 pos;
  433. for(pos.z = 0; pos.z < levels; pos.z++)
  434. {
  435. for(pos.x = 0; pos.x < width; pos.x++)
  436. {
  437. for(pos.y = 0; pos.y < height; pos.y++)
  438. {
  439. distances.clear();
  440. for(auto zone : zones)
  441. {
  442. if (zone.second->getPos().z == pos.z)
  443. distances.push_back(std::make_pair(zone.second, (float)pos.dist2dSQ(zone.second->getPos())));
  444. else
  445. distances.push_back(std::make_pair(zone.second, std::numeric_limits<float>::max()));
  446. }
  447. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  448. }
  449. }
  450. }
  451. for (auto zone : zones)
  452. {
  453. if(zone.second->area().empty())
  454. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  455. moveZoneToCenterOfMass(zone.second);
  456. }
  457. //assign actual tiles to each zone using nonlinear norm for fine edges
  458. for (auto zone : zones)
  459. zone.second->clearTiles(); //now populate them again
  460. for (pos.z = 0; pos.z < levels; pos.z++)
  461. {
  462. for (pos.x = 0; pos.x < width; pos.x++)
  463. {
  464. for (pos.y = 0; pos.y < height; pos.y++)
  465. {
  466. distances.clear();
  467. for (auto zone : zones)
  468. {
  469. if (zone.second->getPos().z == pos.z)
  470. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  471. else
  472. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  473. }
  474. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  475. zone->area().add(pos);
  476. map.setZoneID(pos, zone->getId());
  477. }
  478. }
  479. }
  480. //set position (town position) to center of mass of irregular zone
  481. for (auto zone : zones)
  482. {
  483. moveZoneToCenterOfMass(zone.second);
  484. //TODO: similiar for islands
  485. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  486. if (zone.second->isUnderground())
  487. {
  488. if (!CREATE_FULL_UNDERGROUND)
  489. {
  490. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  491. for(auto& t : discardTiles)
  492. zone.second->area().erase(t);
  493. }
  494. //make sure that terrain inside zone is not a rock
  495. //FIXME: reorder actions?
  496. paintZoneTerrain(*zone.second, *rand, map, Terrain::SUBTERRANEAN);
  497. }
  498. }
  499. logGlobal->info("Finished zone colouring");
  500. }
  501. VCMI_LIB_NAMESPACE_END