CZonePlacer.cpp 24 KB

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