CZonePlacer.cpp 24 KB

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