CZonePlacer.cpp 28 KB

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