CZonePlacer.cpp 26 KB

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