CZonePlacer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 "../CRandomGenerator.h"
  12. #include "CZonePlacer.h"
  13. #include "CRmgTemplateZone.h"
  14. #include "../mapping/CMap.h"
  15. #include "CZoneGraphGenerator.h"
  16. class CRandomGenerator;
  17. CPlacedZone::CPlacedZone(const CRmgTemplateZone * zone)
  18. {
  19. }
  20. CZonePlacer::CZonePlacer(CMapGenerator * Gen) : gen(Gen)
  21. {
  22. }
  23. CZonePlacer::~CZonePlacer()
  24. {
  25. }
  26. int3 CZonePlacer::cords (const float3 f) const
  27. {
  28. return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z);
  29. }
  30. float CZonePlacer::getDistance (float distance) const
  31. {
  32. return (distance ? distance * distance : 1e-6);
  33. }
  34. void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand)
  35. {
  36. logGlobal->infoStream() << "Starting zone placement";
  37. width = mapGenOptions->getWidth();
  38. height = mapGenOptions->getHeight();
  39. auto zones = gen->getZones();
  40. bool underground = mapGenOptions->getHasTwoLevels();
  41. /*
  42. gravity-based algorithm
  43. let's assume we try to fit N circular zones with radius = size on a map
  44. */
  45. gravityConstant = 4e-3;
  46. stiffnessConstant = 4e-3;
  47. TZoneVector zonesVector(zones.begin(), zones.end());
  48. assert (zonesVector.size());
  49. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  50. //0. set zone sizes and surface / underground level
  51. prepareZones(zones, zonesVector, underground, rand);
  52. //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back
  53. //remember best solution
  54. float bestTotalDistance = 1e10;
  55. float bestTotalOverlap = 1e10;
  56. std::map<CRmgTemplateZone *, float3> bestSolution;
  57. TForceVector forces;
  58. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  59. TDistanceVector distances;
  60. TDistanceVector overlaps;
  61. const int MAX_ITERATIONS = 100;
  62. for (int i = 0; i < MAX_ITERATIONS; ++i) //until zones reach their desired size and fill the map tightly
  63. {
  64. //1. attract connected zones
  65. attractConnectedZones(zones, forces, distances);
  66. for (auto zone : forces)
  67. {
  68. zone.first->setCenter (zone.first->getCenter() + zone.second);
  69. totalForces[zone.first] = zone.second; //override
  70. }
  71. //2. separate overlapping zones
  72. separateOverlappingZones(zones, forces, overlaps);
  73. for (auto zone : forces)
  74. {
  75. zone.first->setCenter (zone.first->getCenter() + zone.second);
  76. totalForces[zone.first] += zone.second; //accumulate
  77. }
  78. //3. now perform drastic movement of zone that is completely not linked
  79. moveOneZone(zones, totalForces, distances, overlaps);
  80. //4. NOW after everything was moved, re-evaluate zone positions
  81. attractConnectedZones(zones, forces, distances);
  82. separateOverlappingZones(zones, forces, overlaps);
  83. float totalDistance = 0;
  84. float totalOverlap = 0;
  85. for (auto zone : distances) //find most misplaced zone
  86. {
  87. totalDistance += zone.second;
  88. float overlap = overlaps[zone.first];
  89. totalOverlap += overlap;
  90. }
  91. //check fitness function
  92. bool improvement = false;
  93. if (bestTotalDistance > 0 && bestTotalOverlap > 0)
  94. {
  95. if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
  96. improvement = true;
  97. }
  98. else
  99. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  100. improvement = true;
  101. logGlobal->traceStream() << boost::format("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s") % totalDistance % totalOverlap % improvement;
  102. //save best solution
  103. if (improvement)
  104. {
  105. bestTotalDistance = totalDistance;
  106. bestTotalOverlap = totalOverlap;
  107. for (auto zone : zones)
  108. bestSolution[zone.second] = zone.second->getCenter();
  109. }
  110. }
  111. logGlobal->traceStream() << boost::format("Best fitness reached: total distance %2.4f, total overlap %2.4f") % bestTotalDistance % bestTotalOverlap;
  112. for (auto zone : zones) //finalize zone positions
  113. {
  114. zone.second->setPos (cords (bestSolution[zone.second]));
  115. logGlobal->traceStream() << boost::format ("Placed zone %d at relative position %s and coordinates %s") % zone.first % zone.second->getCenter() % zone.second->getPos();
  116. }
  117. }
  118. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  119. {
  120. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  121. const float radius = 0.4f;
  122. const float pi2 = 6.28f;
  123. int zonesOnLevel[2] = { 0, 0 };
  124. //even distribution for surface / underground zones. Surface zones always have priority.
  125. TZoneVector zonesToPlace;
  126. std::map<TRmgTemplateZoneId, int> levels;
  127. //first pass - determine fixed surface for zones
  128. for (auto zone : zonesVector)
  129. {
  130. if (!underground) //this step is ignored
  131. zonesToPlace.push_back(zone);
  132. else //place players depending on their factions
  133. {
  134. if (boost::optional<int> owner = zone.second->getOwner())
  135. {
  136. auto player = PlayerColor(*owner - 1);
  137. auto playerSettings = gen->mapGenOptions->getPlayersSettings();
  138. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  139. if (vstd::contains(playerSettings, player))
  140. faction = playerSettings[player].getStartingTown();
  141. else
  142. logGlobal->errorStream() << boost::format("Can't find info for player %d (starting zone)") % player.getNum();
  143. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  144. zonesToPlace.push_back(zone);
  145. else
  146. {
  147. switch (VLC->townh->factions[faction]->nativeTerrain)
  148. {
  149. case ETerrainType::GRASS:
  150. case ETerrainType::SWAMP:
  151. case ETerrainType::SNOW:
  152. case ETerrainType::SAND:
  153. case ETerrainType::ROUGH:
  154. //surface
  155. zonesOnLevel[0]++;
  156. levels[zone.first] = 0;
  157. break;
  158. case ETerrainType::LAVA:
  159. case ETerrainType::SUBTERRANEAN:
  160. //underground
  161. zonesOnLevel[1]++;
  162. levels[zone.first] = 1;
  163. break;
  164. case ETerrainType::DIRT:
  165. default:
  166. //any / random
  167. zonesToPlace.push_back(zone);
  168. break;
  169. }
  170. }
  171. }
  172. else //no starting zone or no underground altogether
  173. {
  174. zonesToPlace.push_back(zone);
  175. }
  176. }
  177. }
  178. for (auto zone : zonesToPlace)
  179. {
  180. if (underground) //only then consider underground zones
  181. {
  182. int level = 0;
  183. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  184. level = 1;
  185. else
  186. level = 0;
  187. levels[zone.first] = level;
  188. zonesOnLevel[level]++;
  189. }
  190. else
  191. levels[zone.first] = 0;
  192. }
  193. for (auto zone : zonesVector)
  194. {
  195. int level = levels[zone.first];
  196. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  197. float randomAngle = rand->nextDouble(0, pi2);
  198. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  199. }
  200. /*
  201. prescale zones
  202. formula: sum((prescaler*n)^2)*pi = WH
  203. prescaler = sqrt((WH)/(sum(n^2)*pi))
  204. */
  205. std::vector<float> prescaler = { 0, 0 };
  206. for (int i = 0; i < 2; i++)
  207. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  208. mapSize = sqrt(width * height);
  209. for (auto zone : zones)
  210. {
  211. zone.second->setSize(zone.second->getSize() * prescaler[zone.second->getCenter().z]);
  212. }
  213. }
  214. void CZonePlacer::attractConnectedZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &distances)
  215. {
  216. for (auto zone : zones)
  217. {
  218. float3 forceVector(0, 0, 0);
  219. float3 pos = zone.second->getCenter();
  220. float totalDistance = 0;
  221. for (auto con : zone.second->getConnections())
  222. {
  223. auto otherZone = zones[con];
  224. float3 otherZoneCenter = otherZone->getCenter();
  225. float distance = pos.dist2d(otherZoneCenter);
  226. float minDistance = 0;
  227. if (pos.z != otherZoneCenter.z)
  228. minDistance = 0; //zones on different levels can overlap completely
  229. else
  230. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  231. if (distance > minDistance)
  232. {
  233. //WARNING: compiler used to 'optimize' that line so it never actually worked
  234. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  235. forceVector += (((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance))) * gravityConstant; //positive value
  236. totalDistance += (distance - minDistance);
  237. }
  238. }
  239. distances[zone.second] = totalDistance;
  240. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  241. forces[zone.second] = forceVector;
  242. }
  243. }
  244. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  245. {
  246. for (auto zone : zones)
  247. {
  248. float3 forceVector(0, 0, 0);
  249. float3 pos = zone.second->getCenter();
  250. float overlap = 0;
  251. //separate overlaping zones
  252. for (auto otherZone : zones)
  253. {
  254. float3 otherZoneCenter = otherZone.second->getCenter();
  255. //zones on different levels don't push away
  256. if (zone == otherZone || pos.z != otherZoneCenter.z)
  257. continue;
  258. float distance = pos.dist2d(otherZoneCenter);
  259. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  260. if (distance < minDistance)
  261. {
  262. forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value
  263. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  264. }
  265. }
  266. //move zones away from boundaries
  267. //do not scale boundary distance - zones tend to get squashed
  268. float size = zone.second->getSize() / mapSize;
  269. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  270. {
  271. float3 boundary = float3(x, y, pos.z);
  272. float distance = pos.dist2d(boundary);
  273. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  274. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
  275. };
  276. if (pos.x < size)
  277. {
  278. pushAwayFromBoundary(0, pos.y);
  279. }
  280. if (pos.x > 1 - size)
  281. {
  282. pushAwayFromBoundary(1, pos.y);
  283. }
  284. if (pos.y < size)
  285. {
  286. pushAwayFromBoundary(pos.x, 0);
  287. }
  288. if (pos.y > 1 - size)
  289. {
  290. pushAwayFromBoundary(pos.x, 1);
  291. }
  292. overlaps[zone.second] = overlap;
  293. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  294. forces[zone.second] = forceVector;
  295. }
  296. }
  297. void CZonePlacer::moveOneZone(TZoneMap &zones, TForceVector &totalForces, TDistanceVector &distances, TDistanceVector &overlaps)
  298. {
  299. float maxRatio = 0;
  300. const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected
  301. CRmgTemplateZone * misplacedZone = nullptr;
  302. float totalDistance = 0;
  303. float totalOverlap = 0;
  304. for (auto zone : distances) //find most misplaced zone
  305. {
  306. totalDistance += zone.second;
  307. float overlap = overlaps[zone.first];
  308. totalOverlap += overlap;
  309. float ratio = (zone.second + overlap) / totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  310. if (ratio > maxRatio)
  311. {
  312. maxRatio = ratio;
  313. misplacedZone = zone.first;
  314. }
  315. }
  316. logGlobal->traceStream() << boost::format("Worst misplacement/movement ratio: %3.2f") % maxRatio;
  317. if (maxRatio > maxDistanceMovementRatio)
  318. {
  319. CRmgTemplateZone * targetZone = nullptr;
  320. float3 ourCenter = misplacedZone->getCenter();
  321. if (totalDistance > totalOverlap)
  322. {
  323. //find most distant zone that should be attracted and move inside it
  324. float maxDistance = 0;
  325. for (auto con : misplacedZone->getConnections())
  326. {
  327. auto otherZone = zones[con];
  328. float distance = otherZone->getCenter().dist2dSQ(ourCenter);
  329. if (distance > maxDistance)
  330. {
  331. maxDistance = distance;
  332. targetZone = otherZone;
  333. }
  334. }
  335. float3 vec = targetZone->getCenter() - ourCenter;
  336. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  337. logGlobal->traceStream() << boost::format("Trying to move zone %d %s towards %d %s. Old distance %f") %
  338. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxDistance;
  339. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  340. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  341. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  342. }
  343. else
  344. {
  345. float maxOverlap = 0;
  346. for (auto otherZone : zones)
  347. {
  348. float3 otherZoneCenter = otherZone.second->getCenter();
  349. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  350. continue;
  351. float distance = otherZoneCenter.dist2dSQ(ourCenter);
  352. if (distance > maxOverlap)
  353. {
  354. maxOverlap = distance;
  355. targetZone = otherZone.second;
  356. }
  357. }
  358. float3 vec = ourCenter - targetZone->getCenter();
  359. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  360. logGlobal->traceStream() << boost::format("Trying to move zone %d %s away from %d %s. Old distance %f") %
  361. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxOverlap;
  362. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  363. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  364. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  365. }
  366. }
  367. }
  368. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  369. {
  370. /*
  371. Matlab code
  372. dx = abs(A(1) - B(1)); %distance must be symmetric
  373. dy = abs(A(2) - B(2));
  374. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  375. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  376. */
  377. float dx = abs(A.x - B.x) * scaleX;
  378. float dy = abs(A.y - B.y) * scaleY;
  379. //Horner scheme
  380. return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618));
  381. }
  382. void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions)
  383. {
  384. logGlobal->infoStream() << "Starting zone colouring";
  385. auto width = mapGenOptions->getWidth();
  386. auto height = mapGenOptions->getHeight();
  387. //scale to Medium map to ensure smooth results
  388. scaleX = 72.f / width;
  389. scaleY = 72.f / height;
  390. auto zones = gen->getZones();
  391. typedef std::pair<CRmgTemplateZone *, float> Dpair;
  392. std::vector <Dpair> distances;
  393. distances.reserve(zones.size());
  394. //now place zones correctly and assign tiles to each zone
  395. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  396. {
  397. //bigger zones have smaller distance
  398. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  399. };
  400. auto moveZoneToCenterOfMass = [](CRmgTemplateZone * zone) -> void
  401. {
  402. int3 total(0, 0, 0);
  403. auto tiles = zone->getTileInfo();
  404. for (auto tile : tiles)
  405. {
  406. total += tile;
  407. }
  408. int size = tiles.size();
  409. assert(size);
  410. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  411. };
  412. int levels = gen->map->twoLevel ? 2 : 1;
  413. /*
  414. 1. Create Voronoi diagram
  415. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  416. */
  417. for (int i = 0; i<width; i++)
  418. {
  419. for (int j = 0; j<height; j++)
  420. {
  421. for (int k = 0; k < levels; k++)
  422. {
  423. distances.clear();
  424. int3 pos(i, j, k);
  425. for (auto zone : zones)
  426. {
  427. if (zone.second->getPos().z == k)
  428. distances.push_back(std::make_pair(zone.second, pos.dist2dSQ(zone.second->getPos())));
  429. else
  430. distances.push_back(std::make_pair(zone.second, std::numeric_limits<float>::max()));
  431. }
  432. boost::min_element(distances, compareByDistance)->first->addTile(pos); //closest tile belongs to zone
  433. }
  434. }
  435. }
  436. for (auto zone : zones)
  437. moveZoneToCenterOfMass(zone.second);
  438. //assign actual tiles to each zone using nonlinear norm for fine edges
  439. for (auto zone : zones)
  440. zone.second->clearTiles(); //now populate them again
  441. for (int i=0; i<width; i++)
  442. {
  443. for(int j=0; j<height; j++)
  444. {
  445. for (int k = 0; k < levels; k++)
  446. {
  447. distances.clear();
  448. int3 pos(i, j, k);
  449. for (auto zone : zones)
  450. {
  451. if (zone.second->getPos().z == k)
  452. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  453. else
  454. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  455. }
  456. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  457. zone->addTile(pos);
  458. gen->setZoneID(pos, zone->getId());
  459. }
  460. }
  461. }
  462. //set position (town position) to center of mass of irregular zone
  463. for (auto zone : zones)
  464. {
  465. moveZoneToCenterOfMass(zone.second);
  466. //TODO: similiar for islands
  467. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  468. if (zone.second->getPos().z)
  469. {
  470. if (!CREATE_FULL_UNDERGROUND)
  471. zone.second->discardDistantTiles(gen, zone.second->getSize() + 1);
  472. //make sure that terrain inside zone is not a rock
  473. //FIXME: reorder actions?
  474. zone.second->paintZoneTerrain (gen, ETerrainType::SUBTERRANEAN);
  475. }
  476. }
  477. logGlobal->infoStream() << "Finished zone colouring";
  478. }