CZonePlacer.cpp 29 KB

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