CZonePlacer.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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 <stack>
  12. #include "../CRandomGenerator.h"
  13. #include "CZonePlacer.h"
  14. #include "../TerrainHandler.h"
  15. #include "../mapping/CMap.h"
  16. #include "../mapping/CMapEditManager.h"
  17. #include "CMapGenOptions.h"
  18. #include "RmgMap.h"
  19. #include "Zone.h"
  20. #include "Functions.h"
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. class CRandomGenerator;
  23. CZonePlacer::CZonePlacer(RmgMap & map)
  24. : width(0), height(0), scaleX(0), scaleY(0), mapSize(0),
  25. gravityConstant(1e-3f),
  26. stiffnessConstant(3e-3f),
  27. stifness(0),
  28. stiffnessIncreaseFactor(1.03f),
  29. bestTotalDistance(1e10),
  30. bestTotalOverlap(1e10),
  31. map(map)
  32. {
  33. }
  34. int3 CZonePlacer::cords(const float3 & f) const
  35. {
  36. return int3(static_cast<si32>(std::max(0.f, (f.x * map.map().width) - 1)), static_cast<si32>(std::max(0.f, (f.y * map.map().height - 1))), f.z);
  37. }
  38. float CZonePlacer::getDistance (float distance) const
  39. {
  40. return (distance ? distance * distance : 1e-6f);
  41. }
  42. void CZonePlacer::findPathsBetweenZones()
  43. {
  44. auto zones = map.getZones();
  45. std::set<std::shared_ptr<Zone>> zonesToCheck;
  46. // Iterate through each pair of nodes in the graph
  47. for (const auto& zone : zones)
  48. {
  49. int start = zone.first;
  50. distancesBetweenZones[start][start] = 0; // Distance from a node to itself is 0
  51. std::queue<int> q;
  52. std::map<int, bool> visited;
  53. visited[start] = true;
  54. q.push(start);
  55. // Perform Breadth-First Search from the starting node
  56. while (!q.empty())
  57. {
  58. int current = q.front();
  59. q.pop();
  60. const auto& currentZone = zones.at(current);
  61. const auto& connections = currentZone->getConnections();
  62. for (uint32_t neighbor : connections)
  63. {
  64. if (!visited[neighbor])
  65. {
  66. visited[neighbor] = true;
  67. q.push(neighbor);
  68. distancesBetweenZones[start][neighbor] = distancesBetweenZones[start][current] + 1;
  69. }
  70. }
  71. }
  72. }
  73. }
  74. void CZonePlacer::placeOnGrid(CRandomGenerator* rand)
  75. {
  76. auto zones = map.getZones();
  77. assert(zones.size());
  78. //Make sure there are at least as many grid fields as the number of zones
  79. size_t gridSize = std::ceil(std::sqrt(zones.size()));
  80. typedef boost::multi_array<std::shared_ptr<Zone>, 2> GridType;
  81. GridType grid(boost::extents[gridSize][gridSize]);
  82. TZoneVector zonesVector(zones.begin(), zones.end());
  83. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  84. //Place first zone
  85. auto firstZone = zonesVector[0].second;
  86. size_t x = 0, y = 0;
  87. auto getRandomEdge = [rand, gridSize](size_t& x, size_t& y)
  88. {
  89. switch (rand->nextInt() % 4)
  90. {
  91. case 0:
  92. x = 0;
  93. y = gridSize / 2;
  94. break;
  95. case 1:
  96. x = gridSize - 1;
  97. y = gridSize / 2;
  98. break;
  99. case 2:
  100. x = gridSize / 2;
  101. y = 0;
  102. break;
  103. case 3:
  104. x = gridSize / 2;
  105. y = gridSize - 1;
  106. break;
  107. }
  108. };
  109. switch (firstZone->getType())
  110. {
  111. case ETemplateZoneType::PLAYER_START:
  112. case ETemplateZoneType::CPU_START:
  113. if (firstZone->getConnections().size() > 2)
  114. {
  115. getRandomEdge(x, y);
  116. }
  117. else
  118. {
  119. //Random corner
  120. if (rand->nextInt() % 2)
  121. {
  122. x = 0;
  123. }
  124. else
  125. {
  126. x = gridSize - 1;
  127. }
  128. if (rand->nextInt() % 2)
  129. {
  130. y = 0;
  131. }
  132. else
  133. {
  134. y = gridSize - 1;
  135. }
  136. }
  137. break;
  138. case ETemplateZoneType::TREASURE:
  139. if (gridSize & 1) //odd
  140. {
  141. x = y = (gridSize / 2);
  142. }
  143. else
  144. {
  145. //One of 4 squares in the middle
  146. x = (gridSize / 2) - 1 + rand->nextInt() % 2;
  147. y = (gridSize / 2) - 1 + rand->nextInt() % 2;
  148. }
  149. break;
  150. case ETemplateZoneType::JUNCTION:
  151. getRandomEdge(x, y);
  152. break;
  153. }
  154. grid[x][y] = firstZone;
  155. //Ignore z placement for simplicity
  156. for (size_t i = 1; i < zones.size(); i++)
  157. {
  158. auto zone = zonesVector[i].second;
  159. auto connections = zone->getConnections();
  160. float maxDistance = -1000.0;
  161. int3 mostDistantPlace;
  162. //Iterate over free positions
  163. for (size_t freeX = 0; freeX < gridSize; ++freeX)
  164. {
  165. for (size_t freeY = 0; freeY < gridSize; ++freeY)
  166. {
  167. if (!grid[freeX][freeY])
  168. {
  169. //There is free space left here
  170. int3 potentialPos(freeX, freeY, 0);
  171. //Compute distance to every existing zone
  172. float distance = 0;
  173. for (size_t existingX = 0; existingX < gridSize; ++existingX)
  174. {
  175. for (size_t existingY = 0; existingY < gridSize; ++existingY)
  176. {
  177. auto existingZone = grid[existingX][existingY];
  178. if (existingZone)
  179. {
  180. //There is already zone here
  181. float localDistance = 0.0f;
  182. auto graphDistance = distancesBetweenZones[zone->getId()][existingZone->getId()];
  183. if (graphDistance > 1)
  184. {
  185. //No direct connection
  186. localDistance = potentialPos.dist2d(int3(existingX, existingY, 0)) * graphDistance;
  187. }
  188. else
  189. {
  190. //Has direct connection - place as close as possible
  191. localDistance = -potentialPos.dist2d(int3(existingX, existingY, 0));
  192. }
  193. //Spread apart player starting zones
  194. auto zoneType = zone->getType();
  195. auto existingZoneType = existingZone->getType();
  196. if ((zoneType == ETemplateZoneType::PLAYER_START || zoneType == ETemplateZoneType::CPU_START) &&
  197. (existingZoneType == ETemplateZoneType::PLAYER_START || existingZoneType == ETemplateZoneType::CPU_START))
  198. {
  199. int firstPlayer = zone->getOwner().value();
  200. int secondPlayer = existingZone->getOwner().value();
  201. //Players with lower indexes (especially 1 and 2) will be placed further apart
  202. localDistance *= (1.0f + (2.0f / (firstPlayer * secondPlayer)));
  203. }
  204. distance += localDistance;
  205. }
  206. }
  207. }
  208. if (distance > maxDistance)
  209. {
  210. maxDistance = distance;
  211. mostDistantPlace = potentialPos;
  212. }
  213. }
  214. }
  215. }
  216. //Place in a free slot
  217. grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
  218. }
  219. //TODO: toggle with a flag
  220. logGlobal->info("Initial zone grid:");
  221. for (size_t x = 0; x < gridSize; ++x)
  222. {
  223. std::string s;
  224. for (size_t y = 0; y < gridSize; ++y)
  225. {
  226. if (grid[x][y])
  227. {
  228. s += (boost::format("%3d ") % grid[x][y]->getId()).str();
  229. }
  230. else
  231. {
  232. s += " -- ";
  233. }
  234. }
  235. logGlobal->info(s);
  236. }
  237. //Set initial position for zones - random position in square centered around (x, y)
  238. for (size_t x = 0; x < gridSize; ++x)
  239. {
  240. for (size_t y = 0; y < gridSize; ++y)
  241. {
  242. auto zone = grid[x][y];
  243. if (zone)
  244. {
  245. //i.e. for grid size 5 we get range (0.25 - 4.75)
  246. auto targetX = rand->nextDouble(x + 0.25f, x + 0.75f);
  247. vstd::abetween(targetX, 0.5, gridSize - 0.5);
  248. auto targetY = rand->nextDouble(y + 0.25f, y + 0.75f);
  249. vstd::abetween(targetY, 0.5, gridSize - 0.5);
  250. zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
  251. }
  252. }
  253. }
  254. }
  255. void CZonePlacer::placeZones(CRandomGenerator * rand)
  256. {
  257. logGlobal->info("Starting zone placement");
  258. width = map.getMapGenOptions().getWidth();
  259. height = map.getMapGenOptions().getHeight();
  260. auto zones = map.getZones();
  261. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  262. {
  263. return pr.second->getType() == ETemplateZoneType::WATER;
  264. });
  265. bool underground = map.getMapGenOptions().getHasTwoLevels();
  266. findPathsBetweenZones();
  267. placeOnGrid(rand);
  268. /*
  269. Fruchterman-Reingold algorithm
  270. Let's assume we try to fit N circular zones with radius = size on a map
  271. Connected zones attract, intersecting zones and map boundaries push back
  272. */
  273. TZoneVector zonesVector(zones.begin(), zones.end());
  274. assert (zonesVector.size());
  275. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  276. //0. set zone sizes and surface / underground level
  277. prepareZones(zones, zonesVector, underground, rand);
  278. std::map<std::shared_ptr<Zone>, float3> bestSolution;
  279. TForceVector forces;
  280. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  281. TDistanceVector distances;
  282. TDistanceVector overlaps;
  283. //Start with low stiffness. Bigger graphs need more time and more flexibility
  284. for (stifness = stiffnessConstant / zones.size(); stifness <= stiffnessConstant; stifness *= stiffnessIncreaseFactor)
  285. {
  286. //1. attract connected zones
  287. attractConnectedZones(zones, forces, distances);
  288. for(const auto & zone : forces)
  289. {
  290. zone.first->setCenter (zone.first->getCenter() + zone.second);
  291. totalForces[zone.first] = zone.second; //override
  292. }
  293. //2. separate overlapping zones
  294. separateOverlappingZones(zones, forces, overlaps);
  295. for(const auto & zone : forces)
  296. {
  297. zone.first->setCenter (zone.first->getCenter() + zone.second);
  298. totalForces[zone.first] += zone.second; //accumulate
  299. }
  300. //3. now perform drastic movement of zone that is completely not linked
  301. moveOneZone(zones, totalForces, distances, overlaps);
  302. //4. NOW after everything was moved, re-evaluate zone positions
  303. attractConnectedZones(zones, forces, distances);
  304. separateOverlappingZones(zones, forces, overlaps);
  305. float totalDistance = 0;
  306. float totalOverlap = 0;
  307. for(const auto & zone : distances) //find most misplaced zone
  308. {
  309. totalDistance += zone.second;
  310. float overlap = overlaps[zone.first];
  311. totalOverlap += overlap;
  312. }
  313. //check fitness function
  314. bool improvement = false;
  315. if ((totalDistance + 1) * (totalOverlap + 1) < (bestTotalDistance + 1) * (bestTotalOverlap + 1))
  316. {
  317. //multiplication is better for auto-scaling, but stops working if one factor is 0
  318. improvement = true;
  319. }
  320. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  321. //save best solution
  322. if (improvement)
  323. {
  324. bestTotalDistance = totalDistance;
  325. bestTotalOverlap = totalOverlap;
  326. for(const auto & zone : zones)
  327. bestSolution[zone.second] = zone.second->getCenter();
  328. }
  329. }
  330. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  331. for(const auto & zone : zones) //finalize zone positions
  332. {
  333. zone.second->setPos (cords (bestSolution[zone.second]));
  334. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  335. }
  336. }
  337. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  338. {
  339. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  340. int zonesOnLevel[2] = { 0, 0 };
  341. //even distribution for surface / underground zones. Surface zones always have priority.
  342. TZoneVector zonesToPlace;
  343. std::map<TRmgTemplateZoneId, int> levels;
  344. //first pass - determine fixed surface for zones
  345. for(const auto & zone : zonesVector)
  346. {
  347. if (!underground) //this step is ignored
  348. zonesToPlace.push_back(zone);
  349. else //place players depending on their factions
  350. {
  351. if(std::optional<int> owner = zone.second->getOwner())
  352. {
  353. auto player = PlayerColor(*owner - 1);
  354. auto playerSettings = map.getMapGenOptions().getPlayersSettings();
  355. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  356. if (vstd::contains(playerSettings, player))
  357. faction = playerSettings[player].getStartingTown();
  358. else
  359. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  360. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  361. zonesToPlace.push_back(zone);
  362. else
  363. {
  364. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  365. if(tt == ETerrainId::NONE)
  366. {
  367. //any / random
  368. zonesToPlace.push_back(zone);
  369. }
  370. else
  371. {
  372. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  373. if(terrainType->isUnderground() && !terrainType->isSurface())
  374. {
  375. //underground only
  376. zonesOnLevel[1]++;
  377. levels[zone.first] = 1;
  378. }
  379. else
  380. {
  381. //surface
  382. zonesOnLevel[0]++;
  383. levels[zone.first] = 0;
  384. }
  385. }
  386. }
  387. }
  388. else //no starting zone or no underground altogether
  389. {
  390. zonesToPlace.push_back(zone);
  391. }
  392. }
  393. }
  394. for(const auto & zone : zonesToPlace)
  395. {
  396. if (underground) //only then consider underground zones
  397. {
  398. int level = 0;
  399. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  400. level = 1;
  401. else
  402. level = 0;
  403. levels[zone.first] = level;
  404. zonesOnLevel[level]++;
  405. }
  406. else
  407. levels[zone.first] = 0;
  408. }
  409. for(const auto & zone : zonesVector)
  410. {
  411. int level = levels[zone.first];
  412. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  413. float3 center = zone.second->getCenter();
  414. center.z = level;
  415. zone.second->setCenter(center);
  416. }
  417. /*
  418. prescale zones
  419. formula: sum((prescaler*n)^2)*pi = WH
  420. prescaler = sqrt((WH)/(sum(n^2)*pi))
  421. */
  422. std::vector<float> prescaler = { 0, 0 };
  423. for (int i = 0; i < 2; i++)
  424. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  425. mapSize = static_cast<float>(sqrt(width * height));
  426. for(const auto & zone : zones)
  427. {
  428. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  429. }
  430. }
  431. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  432. {
  433. for(const auto & zone : zones)
  434. {
  435. float3 forceVector(0, 0, 0);
  436. float3 pos = zone.second->getCenter();
  437. float totalDistance = 0;
  438. for (auto con : zone.second->getConnections())
  439. {
  440. auto otherZone = zones[con];
  441. float3 otherZoneCenter = otherZone->getCenter();
  442. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  443. forceVector += (otherZoneCenter - pos) * distance * gravityConstant; //positive value
  444. //Attract zone centers always
  445. float minDistance = 0;
  446. if (pos.z != otherZoneCenter.z)
  447. minDistance = 0; //zones on different levels can overlap completely
  448. else
  449. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  450. if (distance > minDistance)
  451. totalDistance += (distance - minDistance);
  452. }
  453. distances[zone.second] = totalDistance;
  454. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  455. forces[zone.second] = forceVector;
  456. }
  457. }
  458. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  459. {
  460. for(const auto & zone : zones)
  461. {
  462. float3 forceVector(0, 0, 0);
  463. float3 pos = zone.second->getCenter();
  464. float overlap = 0;
  465. //separate overlapping zones
  466. for(const auto & otherZone : zones)
  467. {
  468. float3 otherZoneCenter = otherZone.second->getCenter();
  469. //zones on different levels don't push away
  470. if (zone == otherZone || pos.z != otherZoneCenter.z)
  471. continue;
  472. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  473. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  474. if (distance < minDistance)
  475. {
  476. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  477. //negative value
  478. forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
  479. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  480. }
  481. }
  482. //move zones away from boundaries
  483. //do not scale boundary distance - zones tend to get squashed
  484. float size = zone.second->getSize() / mapSize;
  485. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  486. {
  487. float3 boundary = float3(x, y, pos.z);
  488. auto distance = static_cast<float>(pos.dist2d(boundary));
  489. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  490. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
  491. };
  492. if (pos.x < size)
  493. {
  494. pushAwayFromBoundary(0, pos.y);
  495. }
  496. if (pos.x > 1 - size)
  497. {
  498. pushAwayFromBoundary(1, pos.y);
  499. }
  500. if (pos.y < size)
  501. {
  502. pushAwayFromBoundary(pos.x, 0);
  503. }
  504. if (pos.y > 1 - size)
  505. {
  506. pushAwayFromBoundary(pos.x, 1);
  507. }
  508. overlaps[zone.second] = overlap;
  509. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  510. forces[zone.second] = forceVector;
  511. }
  512. }
  513. void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
  514. {
  515. const int maxDistanceMovementRatio = zones.size() * zones.size(); //The more zones, the greater total distance expected
  516. typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
  517. std::vector<Misplacement> misplacedZones;
  518. float totalDistance = 0;
  519. float totalOverlap = 0;
  520. for (const auto& zone : distances) //find most misplaced zone
  521. {
  522. if (vstd::contains(lastSwappedZones, zone.first->getId()))
  523. {
  524. continue;
  525. }
  526. totalDistance += zone.second;
  527. float overlap = overlaps[zone.first];
  528. totalOverlap += overlap;
  529. //if distance to actual movement is long, the zone is misplaced
  530. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
  531. if (ratio > maxDistanceMovementRatio)
  532. {
  533. misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
  534. }
  535. }
  536. if (misplacedZones.empty())
  537. return;
  538. boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
  539. {
  540. return lhs.first > rhs.first; //Biggest first
  541. });
  542. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
  543. if (misplacedZones.size() >= 2)
  544. {
  545. //Swap 2 misplaced zones
  546. auto firstZone = misplacedZones.front().second;
  547. std::shared_ptr<Zone> secondZone;
  548. auto level = firstZone->getCenter().z;
  549. for (size_t i = 1; i < misplacedZones.size(); i++)
  550. {
  551. //Only swap zones on the same level
  552. //Don't swap zones that should be connected (Jebus)
  553. if (misplacedZones[i].second->getCenter().z == level &&
  554. !vstd::contains(firstZone->getConnections(), misplacedZones[i].second->getId()))
  555. {
  556. secondZone = misplacedZones[i].second;
  557. break;
  558. }
  559. }
  560. if (secondZone)
  561. {
  562. logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
  563. auto firstCenter = firstZone->getCenter();
  564. auto secondCenter = secondZone->getCenter();
  565. firstZone->setCenter(secondCenter);
  566. secondZone->setCenter(firstCenter);
  567. lastSwappedZones.insert(firstZone->getId());
  568. lastSwappedZones.insert(secondZone->getId());
  569. return;
  570. }
  571. }
  572. lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
  573. //find most distant zone that should be attracted and move inside it
  574. std::shared_ptr<Zone> targetZone;
  575. auto misplacedZone = misplacedZones.front().second;
  576. float3 ourCenter = misplacedZone->getCenter();
  577. if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
  578. {
  579. //Move one zone towards most distant zone to reduce distance
  580. float maxDistance = 0;
  581. for (auto con : misplacedZone->getConnections())
  582. {
  583. auto otherZone = zones[con];
  584. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  585. if (distance > maxDistance)
  586. {
  587. maxDistance = distance;
  588. targetZone = otherZone;
  589. }
  590. }
  591. if (targetZone)
  592. {
  593. float3 vec = targetZone->getCenter() - ourCenter;
  594. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  595. logGlobal->trace("Trying to move zone %d %s towards %d %s. Direction is %s", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), vec.toString());
  596. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  597. }
  598. }
  599. else
  600. {
  601. //Move misplaced zone away from overlapping zone
  602. float maxOverlap = 0;
  603. for(const auto & otherZone : zones)
  604. {
  605. float3 otherZoneCenter = otherZone.second->getCenter();
  606. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  607. continue;
  608. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  609. if (distance > maxOverlap)
  610. {
  611. maxOverlap = distance;
  612. targetZone = otherZone.second;
  613. }
  614. }
  615. if (targetZone)
  616. {
  617. float3 vec = ourCenter - targetZone->getCenter();
  618. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  619. logGlobal->trace("Trying to move zone %d %s away from %d %s. Direction is %s", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), vec.toString());
  620. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  621. }
  622. }
  623. //Don't swap that zone in next iteration
  624. lastSwappedZones.insert(misplacedZone->getId());
  625. }
  626. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  627. {
  628. float dx = abs(A.x - B.x) * scaleX;
  629. float dy = abs(A.y - B.y) * scaleY;
  630. /*
  631. 1. Normal euclidean distance
  632. 2. Sinus for extra curves
  633. 3. Nonlinear mess for fuzzy edges
  634. */
  635. return dx * dx + dy * dy +
  636. 5 * std::sin(dx * dy / 10) +
  637. 25 * std::sin (std::sqrt(A.x * B.x) * (A.y - B.y) / 100 * (scaleX * scaleY));
  638. }
  639. void CZonePlacer::assignZones(CRandomGenerator * rand)
  640. {
  641. logGlobal->info("Starting zone colouring");
  642. auto width = map.getMapGenOptions().getWidth();
  643. auto height = map.getMapGenOptions().getHeight();
  644. //scale to Medium map to ensure smooth results
  645. scaleX = 72.f / width;
  646. scaleY = 72.f / height;
  647. auto zones = map.getZones();
  648. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  649. {
  650. return pr.second->getType() == ETemplateZoneType::WATER;
  651. });
  652. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  653. std::vector <Dpair> distances;
  654. distances.reserve(zones.size());
  655. //now place zones correctly and assign tiles to each zone
  656. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  657. {
  658. //bigger zones have smaller distance
  659. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  660. };
  661. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  662. {
  663. int3 total(0, 0, 0);
  664. auto tiles = zone->area().getTiles();
  665. for(const auto & tile : tiles)
  666. {
  667. total += tile;
  668. }
  669. int size = static_cast<int>(tiles.size());
  670. assert(size);
  671. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  672. };
  673. int levels = map.map().levels();
  674. /*
  675. 1. Create Voronoi diagram
  676. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  677. */
  678. int3 pos;
  679. for(pos.z = 0; pos.z < levels; pos.z++)
  680. {
  681. for(pos.x = 0; pos.x < width; pos.x++)
  682. {
  683. for(pos.y = 0; pos.y < height; pos.y++)
  684. {
  685. distances.clear();
  686. for(const auto & zone : zones)
  687. {
  688. if (zone.second->getPos().z == pos.z)
  689. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  690. else
  691. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  692. }
  693. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  694. }
  695. }
  696. }
  697. for(const auto & zone : zones)
  698. {
  699. if(zone.second->area().empty())
  700. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  701. moveZoneToCenterOfMass(zone.second);
  702. }
  703. //assign actual tiles to each zone using nonlinear norm for fine edges
  704. for(const auto & zone : zones)
  705. zone.second->clearTiles(); //now populate them again
  706. for (pos.z = 0; pos.z < levels; pos.z++)
  707. {
  708. for (pos.x = 0; pos.x < width; pos.x++)
  709. {
  710. for (pos.y = 0; pos.y < height; pos.y++)
  711. {
  712. distances.clear();
  713. for(const auto & zone : zones)
  714. {
  715. if (zone.second->getPos().z == pos.z)
  716. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  717. else
  718. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  719. }
  720. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  721. zone->area().add(pos);
  722. map.setZoneID(pos, zone->getId());
  723. }
  724. }
  725. }
  726. //set position (town position) to center of mass of irregular zone
  727. for(const auto & zone : zones)
  728. {
  729. moveZoneToCenterOfMass(zone.second);
  730. //TODO: similiar for islands
  731. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  732. if (zone.second->isUnderground())
  733. {
  734. if (!CREATE_FULL_UNDERGROUND)
  735. {
  736. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  737. for(const auto & t : discardTiles)
  738. zone.second->area().erase(t);
  739. }
  740. //make sure that terrain inside zone is not a rock
  741. //FIXME: reorder actions?
  742. paintZoneTerrain(*zone.second, *rand, map, ETerrainId::SUBTERRANEAN);
  743. }
  744. }
  745. logGlobal->info("Finished zone colouring");
  746. }
  747. VCMI_LIB_NAMESPACE_END