CZonePlacer.cpp 26 KB

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