CZonePlacer.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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.width()) - 1)), static_cast<si32>(std::max(0.f, (f.y * 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 (zone->getOwner() && existingZone->getOwner()) //Players participate in game
  197. {
  198. int firstPlayer = zone->getOwner().value();
  199. int secondPlayer = existingZone->getOwner().value();
  200. //Players with lower indexes (especially 1 and 2) will be placed further apart
  201. localDistance *= (1.0f + (2.0f / (firstPlayer * secondPlayer)));
  202. }
  203. distance += localDistance;
  204. }
  205. }
  206. }
  207. if (distance > maxDistance)
  208. {
  209. maxDistance = distance;
  210. mostDistantPlace = potentialPos;
  211. }
  212. }
  213. }
  214. }
  215. //Place in a free slot
  216. grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
  217. }
  218. //TODO: toggle with a flag
  219. logGlobal->info("Initial zone grid:");
  220. for (size_t x = 0; x < gridSize; ++x)
  221. {
  222. std::string s;
  223. for (size_t y = 0; y < gridSize; ++y)
  224. {
  225. if (grid[x][y])
  226. {
  227. s += (boost::format("%3d ") % grid[x][y]->getId()).str();
  228. }
  229. else
  230. {
  231. s += " -- ";
  232. }
  233. }
  234. logGlobal->info(s);
  235. }
  236. //Set initial position for zones - random position in square centered around (x, y)
  237. for (size_t x = 0; x < gridSize; ++x)
  238. {
  239. for (size_t y = 0; y < gridSize; ++y)
  240. {
  241. auto zone = grid[x][y];
  242. if (zone)
  243. {
  244. //i.e. for grid size 5 we get range (0.25 - 4.75)
  245. auto targetX = rand->nextDouble(x + 0.25f, x + 0.75f);
  246. vstd::abetween(targetX, 0.5, gridSize - 0.5);
  247. auto targetY = rand->nextDouble(y + 0.25f, y + 0.75f);
  248. vstd::abetween(targetY, 0.5, gridSize - 0.5);
  249. zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
  250. }
  251. }
  252. }
  253. }
  254. void CZonePlacer::placeZones(CRandomGenerator * rand)
  255. {
  256. logGlobal->info("Starting zone placement");
  257. width = map.getMapGenOptions().getWidth();
  258. height = map.getMapGenOptions().getHeight();
  259. auto zones = map.getZones();
  260. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  261. {
  262. return pr.second->getType() == ETemplateZoneType::WATER;
  263. });
  264. bool underground = map.getMapGenOptions().getHasTwoLevels();
  265. findPathsBetweenZones();
  266. placeOnGrid(rand);
  267. /*
  268. Fruchterman-Reingold algorithm
  269. Let's assume we try to fit N circular zones with radius = size on a map
  270. Connected zones attract, intersecting zones and map boundaries push back
  271. */
  272. TZoneVector zonesVector(zones.begin(), zones.end());
  273. assert (zonesVector.size());
  274. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  275. //0. set zone sizes and surface / underground level
  276. prepareZones(zones, zonesVector, underground, rand);
  277. std::map<std::shared_ptr<Zone>, float3> bestSolution;
  278. TForceVector forces;
  279. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  280. TDistanceVector distances;
  281. TDistanceVector overlaps;
  282. //Start with low stiffness. Bigger graphs need more time and more flexibility
  283. for (stifness = stiffnessConstant / zones.size(); stifness <= stiffnessConstant; stifness *= stiffnessIncreaseFactor)
  284. {
  285. //1. attract connected zones
  286. attractConnectedZones(zones, forces, distances);
  287. for(const auto & zone : forces)
  288. {
  289. zone.first->setCenter (zone.first->getCenter() + zone.second);
  290. totalForces[zone.first] = zone.second; //override
  291. }
  292. //2. separate overlapping zones
  293. separateOverlappingZones(zones, forces, overlaps);
  294. for(const auto & zone : forces)
  295. {
  296. zone.first->setCenter (zone.first->getCenter() + zone.second);
  297. totalForces[zone.first] += zone.second; //accumulate
  298. }
  299. //3. now perform drastic movement of zone that is completely not linked
  300. moveOneZone(zones, totalForces, distances, overlaps);
  301. //4. NOW after everything was moved, re-evaluate zone positions
  302. attractConnectedZones(zones, forces, distances);
  303. separateOverlappingZones(zones, forces, overlaps);
  304. float totalDistance = 0;
  305. float totalOverlap = 0;
  306. for(const auto & zone : distances) //find most misplaced zone
  307. {
  308. totalDistance += zone.second;
  309. float overlap = overlaps[zone.first];
  310. totalOverlap += overlap;
  311. }
  312. //check fitness function
  313. bool improvement = false;
  314. if ((totalDistance + 1) * (totalOverlap + 1) < (bestTotalDistance + 1) * (bestTotalOverlap + 1))
  315. {
  316. //multiplication is better for auto-scaling, but stops working if one factor is 0
  317. improvement = true;
  318. }
  319. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  320. //save best solution
  321. if (improvement)
  322. {
  323. bestTotalDistance = totalDistance;
  324. bestTotalOverlap = totalOverlap;
  325. for(const auto & zone : zones)
  326. bestSolution[zone.second] = zone.second->getCenter();
  327. }
  328. }
  329. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  330. for(const auto & zone : zones) //finalize zone positions
  331. {
  332. zone.second->setPos (cords (bestSolution[zone.second]));
  333. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  334. }
  335. }
  336. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  337. {
  338. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  339. int zonesOnLevel[2] = { 0, 0 };
  340. //even distribution for surface / underground zones. Surface zones always have priority.
  341. TZoneVector zonesToPlace;
  342. std::map<TRmgTemplateZoneId, int> levels;
  343. //first pass - determine fixed surface for zones
  344. for(const auto & zone : zonesVector)
  345. {
  346. if (!underground) //this step is ignored
  347. zonesToPlace.push_back(zone);
  348. else //place players depending on their factions
  349. {
  350. if(std::optional<int> owner = zone.second->getOwner())
  351. {
  352. auto player = PlayerColor(*owner - 1);
  353. auto playerSettings = map.getMapGenOptions().getPlayersSettings();
  354. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  355. if (vstd::contains(playerSettings, player))
  356. faction = playerSettings[player].getStartingTown();
  357. else
  358. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  359. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  360. zonesToPlace.push_back(zone);
  361. else
  362. {
  363. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  364. if(tt == ETerrainId::NONE)
  365. {
  366. //any / random
  367. zonesToPlace.push_back(zone);
  368. }
  369. else
  370. {
  371. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  372. if(terrainType->isUnderground() && !terrainType->isSurface())
  373. {
  374. //underground only
  375. zonesOnLevel[1]++;
  376. levels[zone.first] = 1;
  377. }
  378. else
  379. {
  380. //surface
  381. zonesOnLevel[0]++;
  382. levels[zone.first] = 0;
  383. }
  384. }
  385. }
  386. }
  387. else //no starting zone or no underground altogether
  388. {
  389. zonesToPlace.push_back(zone);
  390. }
  391. }
  392. }
  393. for(const auto & zone : zonesToPlace)
  394. {
  395. if (underground) //only then consider underground zones
  396. {
  397. int level = 0;
  398. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  399. level = 1;
  400. else
  401. level = 0;
  402. levels[zone.first] = level;
  403. zonesOnLevel[level]++;
  404. }
  405. else
  406. levels[zone.first] = 0;
  407. }
  408. for(const auto & zone : zonesVector)
  409. {
  410. int level = levels[zone.first];
  411. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  412. float3 center = zone.second->getCenter();
  413. center.z = level;
  414. zone.second->setCenter(center);
  415. }
  416. /*
  417. prescale zones
  418. formula: sum((prescaler*n)^2)*pi = WH
  419. prescaler = sqrt((WH)/(sum(n^2)*pi))
  420. */
  421. std::vector<float> prescaler = { 0, 0 };
  422. for (int i = 0; i < 2; i++)
  423. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  424. mapSize = static_cast<float>(sqrt(width * height));
  425. for(const auto & zone : zones)
  426. {
  427. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  428. }
  429. }
  430. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  431. {
  432. for(const auto & zone : zones)
  433. {
  434. float3 forceVector(0, 0, 0);
  435. float3 pos = zone.second->getCenter();
  436. float totalDistance = 0;
  437. for (auto con : zone.second->getConnections())
  438. {
  439. auto otherZone = zones[con];
  440. float3 otherZoneCenter = otherZone->getCenter();
  441. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  442. forceVector += (otherZoneCenter - pos) * distance * gravityConstant; //positive value
  443. //Attract zone centers always
  444. float minDistance = 0;
  445. if (pos.z != otherZoneCenter.z)
  446. minDistance = 0; //zones on different levels can overlap completely
  447. else
  448. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  449. if (distance > minDistance)
  450. totalDistance += (distance - minDistance);
  451. }
  452. distances[zone.second] = totalDistance;
  453. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  454. forces[zone.second] = forceVector;
  455. }
  456. }
  457. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  458. {
  459. for(const auto & zone : zones)
  460. {
  461. float3 forceVector(0, 0, 0);
  462. float3 pos = zone.second->getCenter();
  463. float overlap = 0;
  464. //separate overlapping zones
  465. for(const auto & otherZone : zones)
  466. {
  467. float3 otherZoneCenter = otherZone.second->getCenter();
  468. //zones on different levels don't push away
  469. if (zone == otherZone || pos.z != otherZoneCenter.z)
  470. continue;
  471. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  472. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  473. if (distance < minDistance)
  474. {
  475. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  476. //negative value
  477. forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
  478. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  479. }
  480. }
  481. //move zones away from boundaries
  482. //do not scale boundary distance - zones tend to get squashed
  483. float size = zone.second->getSize() / mapSize;
  484. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  485. {
  486. float3 boundary = float3(x, y, pos.z);
  487. auto distance = static_cast<float>(pos.dist2d(boundary));
  488. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  489. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
  490. };
  491. if (pos.x < size)
  492. {
  493. pushAwayFromBoundary(0, pos.y);
  494. }
  495. if (pos.x > 1 - size)
  496. {
  497. pushAwayFromBoundary(1, pos.y);
  498. }
  499. if (pos.y < size)
  500. {
  501. pushAwayFromBoundary(pos.x, 0);
  502. }
  503. if (pos.y > 1 - size)
  504. {
  505. pushAwayFromBoundary(pos.x, 1);
  506. }
  507. overlaps[zone.second] = overlap;
  508. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  509. forces[zone.second] = forceVector;
  510. }
  511. }
  512. void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
  513. {
  514. const int maxDistanceMovementRatio = zones.size() * zones.size(); //The more zones, the greater total distance expected
  515. typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
  516. std::vector<Misplacement> misplacedZones;
  517. float totalDistance = 0;
  518. float totalOverlap = 0;
  519. for (const auto& zone : distances) //find most misplaced zone
  520. {
  521. if (vstd::contains(lastSwappedZones, zone.first->getId()))
  522. {
  523. continue;
  524. }
  525. totalDistance += zone.second;
  526. float overlap = overlaps[zone.first];
  527. totalOverlap += overlap;
  528. //if distance to actual movement is long, the zone is misplaced
  529. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
  530. if (ratio > maxDistanceMovementRatio)
  531. {
  532. misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
  533. }
  534. }
  535. if (misplacedZones.empty())
  536. return;
  537. boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
  538. {
  539. return lhs.first > rhs.first; //Biggest first
  540. });
  541. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
  542. if (misplacedZones.size() >= 2)
  543. {
  544. //Swap 2 misplaced zones
  545. auto firstZone = misplacedZones.front().second;
  546. std::shared_ptr<Zone> secondZone;
  547. auto level = firstZone->getCenter().z;
  548. for (size_t i = 1; i < misplacedZones.size(); i++)
  549. {
  550. //Only swap zones on the same level
  551. //Don't swap zones that should be connected (Jebus)
  552. if (misplacedZones[i].second->getCenter().z == level &&
  553. !vstd::contains(firstZone->getConnections(), misplacedZones[i].second->getId()))
  554. {
  555. secondZone = misplacedZones[i].second;
  556. break;
  557. }
  558. }
  559. if (secondZone)
  560. {
  561. logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
  562. auto firstCenter = firstZone->getCenter();
  563. auto secondCenter = secondZone->getCenter();
  564. firstZone->setCenter(secondCenter);
  565. secondZone->setCenter(firstCenter);
  566. lastSwappedZones.insert(firstZone->getId());
  567. lastSwappedZones.insert(secondZone->getId());
  568. return;
  569. }
  570. }
  571. lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
  572. //find most distant zone that should be attracted and move inside it
  573. std::shared_ptr<Zone> targetZone;
  574. auto misplacedZone = misplacedZones.front().second;
  575. float3 ourCenter = misplacedZone->getCenter();
  576. if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
  577. {
  578. //Move one zone towards most distant zone to reduce distance
  579. float maxDistance = 0;
  580. for (auto con : misplacedZone->getConnections())
  581. {
  582. auto otherZone = zones[con];
  583. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  584. if (distance > maxDistance)
  585. {
  586. maxDistance = distance;
  587. targetZone = otherZone;
  588. }
  589. }
  590. if (targetZone)
  591. {
  592. float3 vec = targetZone->getCenter() - ourCenter;
  593. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  594. 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());
  595. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  596. }
  597. }
  598. else
  599. {
  600. //Move misplaced zone away from overlapping zone
  601. float maxOverlap = 0;
  602. for(const auto & otherZone : zones)
  603. {
  604. float3 otherZoneCenter = otherZone.second->getCenter();
  605. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  606. continue;
  607. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  608. if (distance > maxOverlap)
  609. {
  610. maxOverlap = distance;
  611. targetZone = otherZone.second;
  612. }
  613. }
  614. if (targetZone)
  615. {
  616. float3 vec = ourCenter - targetZone->getCenter();
  617. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  618. 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());
  619. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  620. }
  621. }
  622. //Don't swap that zone in next iteration
  623. lastSwappedZones.insert(misplacedZone->getId());
  624. }
  625. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  626. {
  627. float dx = abs(A.x - B.x) * scaleX;
  628. float dy = abs(A.y - B.y) * scaleY;
  629. /*
  630. 1. Normal euclidean distance
  631. 2. Sinus for extra curves
  632. 3. Nonlinear mess for fuzzy edges
  633. */
  634. return dx * dx + dy * dy +
  635. 5 * std::sin(dx * dy / 10) +
  636. 25 * std::sin (std::sqrt(A.x * B.x) * (A.y - B.y) / 100 * (scaleX * scaleY));
  637. }
  638. void CZonePlacer::assignZones(CRandomGenerator * rand)
  639. {
  640. logGlobal->info("Starting zone colouring");
  641. auto width = map.getMapGenOptions().getWidth();
  642. auto height = map.getMapGenOptions().getHeight();
  643. //scale to Medium map to ensure smooth results
  644. scaleX = 72.f / width;
  645. scaleY = 72.f / height;
  646. auto zones = map.getZones();
  647. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  648. {
  649. return pr.second->getType() == ETemplateZoneType::WATER;
  650. });
  651. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  652. std::vector <Dpair> distances;
  653. distances.reserve(zones.size());
  654. //now place zones correctly and assign tiles to each zone
  655. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  656. {
  657. //bigger zones have smaller distance
  658. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  659. };
  660. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  661. {
  662. int3 total(0, 0, 0);
  663. auto tiles = zone->area().getTiles();
  664. for(const auto & tile : tiles)
  665. {
  666. total += tile;
  667. }
  668. int size = static_cast<int>(tiles.size());
  669. assert(size);
  670. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  671. };
  672. int levels = map.levels();
  673. /*
  674. 1. Create Voronoi diagram
  675. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  676. */
  677. int3 pos;
  678. for(pos.z = 0; pos.z < levels; pos.z++)
  679. {
  680. for(pos.x = 0; pos.x < width; pos.x++)
  681. {
  682. for(pos.y = 0; pos.y < height; pos.y++)
  683. {
  684. distances.clear();
  685. for(const auto & zone : zones)
  686. {
  687. if (zone.second->getPos().z == pos.z)
  688. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  689. else
  690. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  691. }
  692. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  693. }
  694. }
  695. }
  696. for(const auto & zone : zones)
  697. {
  698. if(zone.second->area().empty())
  699. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  700. moveZoneToCenterOfMass(zone.second);
  701. }
  702. //assign actual tiles to each zone using nonlinear norm for fine edges
  703. for(const auto & zone : zones)
  704. zone.second->clearTiles(); //now populate them again
  705. for (pos.z = 0; pos.z < levels; pos.z++)
  706. {
  707. for (pos.x = 0; pos.x < width; pos.x++)
  708. {
  709. for (pos.y = 0; pos.y < height; pos.y++)
  710. {
  711. distances.clear();
  712. for(const auto & zone : zones)
  713. {
  714. if (zone.second->getPos().z == pos.z)
  715. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  716. else
  717. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  718. }
  719. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  720. zone->area().add(pos);
  721. map.setZoneID(pos, zone->getId());
  722. }
  723. }
  724. }
  725. //set position (town position) to center of mass of irregular zone
  726. for(const auto & zone : zones)
  727. {
  728. moveZoneToCenterOfMass(zone.second);
  729. //TODO: similiar for islands
  730. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  731. if (zone.second->isUnderground())
  732. {
  733. if (!CREATE_FULL_UNDERGROUND)
  734. {
  735. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  736. for(const auto & t : discardTiles)
  737. zone.second->area().erase(t);
  738. }
  739. //make sure that terrain inside zone is not a rock
  740. auto v = zone.second->getArea().getTilesVector();
  741. map.getMapProxy()->drawTerrain(*rand, v, ETerrainId::SUBTERRANEAN);
  742. }
  743. }
  744. logGlobal->info("Finished zone colouring");
  745. }
  746. const TDistanceMap& CZonePlacer::getDistanceMap()
  747. {
  748. return distancesBetweenZones;
  749. }
  750. VCMI_LIB_NAMESPACE_END