1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-11-23 22:37:55 +02:00
Files
vcmi/lib/rmg/CZonePlacer.cpp
2025-08-01 20:05:03 +02:00

1566 lines
44 KiB
C++

/*
* CZonePlacer.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CZonePlacer.h"
#include "../TerrainHandler.h"
#include "../entities/faction/CFaction.h"
#include "../entities/faction/CTownHandler.h"
#include "../mapping/CMap.h"
#include "../mapping/CMapEditManager.h"
#include "../GameLibrary.h"
#include "CMapGenOptions.h"
#include "CRmgTemplate.h"
#include "RmgMap.h"
#include "Zone.h"
#include "Functions.h"
#include "PenroseTiling.h"
#include <vstd/RNG.h>
VCMI_LIB_NAMESPACE_BEGIN
//#define ZONE_PLACEMENT_LOG true
CZonePlacer::CZonePlacer(RmgMap & map)
: width(0), height(0), mapSize(0),
gravityConstant(1e-3f),
stiffnessConstant(3e-3f),
stifness(0),
stiffnessIncreaseFactor(1.03f),
bestTotalDistance(1e10),
bestTotalOverlap(1e10),
map(map)
{
}
int3 CZonePlacer::cords(const float3 & f) const
{
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);
}
float CZonePlacer::getDistance (float distance) const
{
return (distance ? distance * distance : 1e-6f);
}
void CZonePlacer::findPathsBetweenZones()
{
auto zones = map.getZones();
std::set<std::shared_ptr<Zone>> zonesToCheck;
// Iterate through each pair of nodes in the graph
for (const auto& zone : zones)
{
int start = zone.first;
distancesBetweenZones[start][start] = 0; // Distance from a node to itself is 0
std::queue<int> q;
std::map<int, bool> visited;
visited[start] = true;
q.push(start);
// Perform Breadth-First Search from the starting node
while (!q.empty())
{
int current = q.front();
q.pop();
const auto& currentZone = zones.at(current);
const auto& connectedZoneIds = currentZone->getConnections();
for (auto & connection : connectedZoneIds)
{
switch (connection.getConnectionType())
{
//Do not consider virtual connections for graph distance
case rmg::EConnectionType::REPULSIVE:
case rmg::EConnectionType::FORCE_PORTAL:
continue;
}
auto neighbor = connection.getOtherZoneId(current);
if (current == neighbor)
{
//Do not consider self-connections
continue;
}
if (!visited[neighbor])
{
visited[neighbor] = true;
q.push(neighbor);
distancesBetweenZones[start][neighbor] = distancesBetweenZones[start][current] + 1;
}
}
}
}
}
void CZonePlacer::placeOnGrid(vstd::RNG* rand)
{
auto zones = map.getZones();
assert(zones.size());
//Make sure there are at least as many grid fields as the number of zones
size_t gridSize = std::ceil(std::sqrt(zones.size()));
typedef boost::multi_array<std::shared_ptr<Zone>, 2> GridType;
GridType grid(boost::extents[gridSize][gridSize]);
TZoneVector zonesVector(zones.begin(), zones.end());
//Place first zone
auto firstZone = zonesVector[0].second;
size_t x = 0;
size_t y = 0;
auto getRandomEdge = [rand, gridSize](size_t& x, size_t& y)
{
switch (rand->nextInt(0, 3) % 4)
{
case 0:
x = 0;
y = gridSize / 2;
break;
case 1:
x = gridSize - 1;
y = gridSize / 2;
break;
case 2:
x = gridSize / 2;
y = 0;
break;
case 3:
x = gridSize / 2;
y = gridSize - 1;
break;
}
};
switch (firstZone->getType())
{
case ETemplateZoneType::PLAYER_START:
case ETemplateZoneType::CPU_START:
if (firstZone->getConnectedZoneIds().size() > 2)
{
getRandomEdge(x, y);
}
else
{
//Random corner
if (rand->nextInt(0, 1) == 1)
{
x = 0;
}
else
{
x = gridSize - 1;
}
if (rand->nextInt(0, 1) == 1)
{
y = 0;
}
else
{
y = gridSize - 1;
}
}
break;
case ETemplateZoneType::TREASURE:
if (gridSize & 1) //odd
{
x = y = (gridSize / 2);
}
else
{
//One of 4 squares in the middle
x = (gridSize / 2) - 1 + rand->nextInt(0, 1);
y = (gridSize / 2) - 1 + rand->nextInt(0, 1);
}
break;
case ETemplateZoneType::JUNCTION:
getRandomEdge(x, y);
break;
}
grid[x][y] = firstZone;
//Ignore z placement for simplicity
for (size_t i = 1; i < zones.size(); i++)
{
auto zone = zonesVector[i].second;
auto connectedZoneIds = zone->getConnectedZoneIds();
float maxDistance = -1000.0;
int3 mostDistantPlace;
//Iterate over free positions
for (size_t freeX = 0; freeX < gridSize; ++freeX)
{
for (size_t freeY = 0; freeY < gridSize; ++freeY)
{
if (!grid[freeX][freeY])
{
//There is free space left here
int3 potentialPos(freeX, freeY, 0);
//Compute distance to every existing zone
float distance = 0;
for (size_t existingX = 0; existingX < gridSize; ++existingX)
{
for (size_t existingY = 0; existingY < gridSize; ++existingY)
{
auto existingZone = grid[existingX][existingY];
if (existingZone)
{
//There is already zone here
float localDistance = 0.0f;
auto graphDistance = distancesBetweenZones[zone->getId()][existingZone->getId()];
if (graphDistance > 1)
{
//No direct connection
localDistance = potentialPos.dist2d(int3(existingX, existingY, 0)) * graphDistance;
}
else
{
//Has direct connection - place as close as possible
localDistance = -potentialPos.dist2d(int3(existingX, existingY, 0));
}
localDistance *= scaleForceBetweenZones(zone, existingZone);
distance += localDistance;
}
}
}
if (distance > maxDistance)
{
maxDistance = distance;
mostDistantPlace = potentialPos;
}
}
}
}
//Place in a free slot
grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
}
//TODO: toggle with a flag
#ifdef ZONE_PLACEMENT_LOG
logGlobal->trace("Initial zone grid:");
for (size_t x = 0; x < gridSize; ++x)
{
std::string s;
for (size_t y = 0; y < gridSize; ++y)
{
if (grid[x][y])
{
s += (boost::format("%3d ") % grid[x][y]->getId()).str();
}
else
{
s += " -- ";
}
}
logGlobal->trace(s);
}
#endif
//Set initial position for zones - random position in square centered around (x, y)
for (size_t x = 0; x < gridSize; ++x)
{
for (size_t y = 0; y < gridSize; ++y)
{
auto zone = grid[x][y];
if (zone)
{
//i.e. for grid size 5 we get range (0.25 - 4.75)
auto targetX = rand->nextDouble(x + 0.25f, x + 0.75f);
vstd::abetween(targetX, 0.5, gridSize - 0.5);
auto targetY = rand->nextDouble(y + 0.25f, y + 0.75f);
vstd::abetween(targetY, 0.5, gridSize - 0.5);
zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
}
}
}
}
float CZonePlacer::scaleForceBetweenZones(const std::shared_ptr<Zone> zoneA, const std::shared_ptr<Zone> zoneB) const
{
if (zoneA->getOwner() && zoneB->getOwner()) //Players participate in game
{
int firstPlayer = zoneA->getOwner().value();
int secondPlayer = zoneB->getOwner().value();
//Players with lower indexes (especially 1 and 2) will be placed further apart
return (1.0f + (2.0f / (firstPlayer * secondPlayer)));
}
else
{
return 1;
}
}
void CZonePlacer::placeZones(vstd::RNG * rand)
{
logGlobal->info("Starting zone placement");
width = map.getMapGenOptions().getWidth();
height = map.getMapGenOptions().getHeight();
auto zones = map.getZones();
vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
{
return pr.second->getType() == ETemplateZoneType::WATER;
});
bool underground = map.getMapGenOptions().getHasTwoLevels();
findPathsBetweenZones();
placeOnGrid(rand);
/*
Fruchterman-Reingold algorithm
Let's assume we try to fit N circular zones with radius = size on a map
Connected zones attract, intersecting zones and map boundaries push back
*/
TZoneVector zonesVector(zones.begin(), zones.end());
assert (zonesVector.size());
RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
//0. set zone sizes and surface / underground level
prepareZones(zones, zonesVector, underground, rand);
std::map<std::shared_ptr<Zone>, float3> bestSolution;
TForceVector forces;
TForceVector totalForces; // both attraction and pushback, overcomplicated?
TDistanceVector distances;
TDistanceVector overlaps;
auto evaluateSolution = [this, zones, &distances, &overlaps, &bestSolution]() -> bool
{
bool improvement = false;
float totalDistance = 0;
float totalOverlap = 0;
for (const auto& zone : distances) //find most misplaced zone
{
totalDistance += zone.second;
float overlap = overlaps[zone.first];
totalOverlap += overlap;
}
//check fitness function
if ((totalDistance + 1) * (totalOverlap + 1) < (bestTotalDistance + 1) * (bestTotalOverlap + 1))
{
//multiplication is better for auto-scaling, but stops working if one factor is 0
improvement = true;
}
//Save best solution
if (improvement)
{
bestTotalDistance = totalDistance;
bestTotalOverlap = totalOverlap;
for (const auto& zone : zones)
bestSolution[zone.second] = zone.second->getCenter();
}
#ifdef ZONE_PLACEMENT_LOG
logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
#endif
return improvement;
};
//Start with low stiffness. Bigger graphs need more time and more flexibility
for (stifness = stiffnessConstant / zones.size(); stifness <= stiffnessConstant;)
{
//1. attract connected zones
attractConnectedZones(zones, forces, distances);
for(const auto & zone : forces)
{
zone.first->setCenter (zone.first->getCenter() + zone.second);
totalForces[zone.first] = zone.second; //override
}
//2. separate overlapping zones
separateOverlappingZones(zones, forces, overlaps);
for(const auto & zone : forces)
{
zone.first->setCenter (zone.first->getCenter() + zone.second);
totalForces[zone.first] += zone.second; //accumulate
}
bool improved = evaluateSolution();
if (!improved)
{
//3. now perform drastic movement of zone that is completely not linked
//TODO: Don't do this is fitness was improved
moveOneZone(zones, totalForces, distances, overlaps);
improved |= evaluateSolution();
}
if (!improved)
{
//Only cool down if we didn't see any improvement
stifness *= stiffnessIncreaseFactor;
}
}
logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
for(const auto & zone : zones) //finalize zone positions
{
zone.second->setPos (cords (bestSolution[zone.second]));
#ifdef ZONE_PLACEMENT_LOG
logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
#endif
}
}
void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, vstd::RNG * rand)
{
std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
int zonesOnLevel[2] = { 0, 0 };
//even distribution for surface / underground zones. Surface zones always have priority.
TZoneVector zonesToPlace;
std::map<TRmgTemplateZoneId, int> levels;
//first pass - determine fixed surface for zones
for(const auto & zone : zonesVector)
{
if (!underground) //this step is ignored
zonesToPlace.push_back(zone);
else //place players depending on their factions
{
if(std::optional<int> owner = zone.second->getOwner())
{
auto player = PlayerColor(*owner - 1);
auto playerSettings = map.getMapGenOptions().getPlayersSettings();
FactionID faction = FactionID::RANDOM;
if (playerSettings.size() > player.getNum())
{
faction = std::next(playerSettings.begin(), player.getNum())->second.getStartingTown();
}
else
{
logGlobal->trace("Player %d (starting zone %d) does not participate in game", player.getNum(), zone.first);
}
if (faction == FactionID::RANDOM) //TODO: check this after a town has already been randomized
zonesToPlace.push_back(zone);
else
{
auto & tt = (*LIBRARY->townh)[faction]->nativeTerrain;
if(tt == ETerrainId::NONE)
{
//any / random
zonesToPlace.push_back(zone);
}
else
{
const auto & terrainType = LIBRARY->terrainTypeHandler->getById(tt);
if(terrainType->isUnderground() && !terrainType->isSurface())
{
//underground only
zonesOnLevel[1]++;
levels[zone.first] = 1;
}
else
{
//surface
zonesOnLevel[0]++;
levels[zone.first] = 0;
}
}
}
}
else //no starting zone or no underground altogether
{
zonesToPlace.push_back(zone);
}
}
}
for(const auto & zone : zonesToPlace)
{
if (underground) //only then consider underground zones
{
int level = 0;
if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
level = 1;
else
level = 0;
levels[zone.first] = level;
zonesOnLevel[level]++;
}
else
levels[zone.first] = 0;
}
for(const auto & zone : zonesVector)
{
int level = levels[zone.first];
totalSize[level] += (zone.second->getSize() * zone.second->getSize());
float3 center = zone.second->getCenter();
center.z = level;
zone.second->setCenter(center);
}
/*
prescale zones
formula: sum((prescaler*n)^2)*pi = WH
prescaler = sqrt((WH)/(sum(n^2)*pi))
*/
std::vector<float> prescaler = { 0, 0 };
for (int i = 0; i < 2; i++)
prescaler[i] = std::sqrt((width * height) / (totalSize[i] * PI_CONSTANT));
mapSize = static_cast<float>(sqrt(width * height));
for(const auto & zone : zones)
{
zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
}
}
void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
{
for(const auto & zone : zones)
{
float3 forceVector(0, 0, 0);
float3 pos = zone.second->getCenter();
float totalDistance = 0;
for (const auto & connection : zone.second->getConnections())
{
switch (connection.getConnectionType())
{
//Do not consider virtual connections for graph distance
case rmg::EConnectionType::REPULSIVE:
case rmg::EConnectionType::FORCE_PORTAL:
continue;
}
if (connection.getZoneA() == connection.getZoneB())
{
//Do not consider self-connections
continue;
}
auto otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
float3 otherZoneCenter = otherZone->getCenter();
auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
forceVector += (otherZoneCenter - pos) * distance * gravityConstant * scaleForceBetweenZones(zone.second, otherZone); //positive value
//Attract zone centers always
float minDistance = 0;
if (pos.z != otherZoneCenter.z)
minDistance = 0; //zones on different levels can overlap completely
else
minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
if (distance > minDistance)
totalDistance += (distance - minDistance);
}
distances[zone.second] = totalDistance;
forceVector.z = 0; //operator - doesn't preserve z coordinate :/
forces[zone.second] = forceVector;
}
}
void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
{
for(const auto & zone : zones)
{
float3 forceVector(0, 0, 0);
float3 pos = zone.second->getCenter();
float overlap = 0;
//separate overlapping zones
for(const auto & otherZone : zones)
{
float3 otherZoneCenter = otherZone.second->getCenter();
//zones on different levels don't push away
if (zone == otherZone || pos.z != otherZoneCenter.z)
continue;
auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
if (distance < minDistance)
{
float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
//negative value
localForce *= scaleForceBetweenZones(zone.second, otherZone.second);
forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
overlap += (minDistance - distance); //overlapping of small zones hurts us more
}
}
//move zones away from boundaries
//do not scale boundary distance - zones tend to get squashed
float size = zone.second->getSize() / mapSize;
auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
{
float3 boundary = float3(x, y, pos.z);
auto distance = static_cast<float>(pos.dist2d(boundary));
overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
};
if (pos.x < size)
{
pushAwayFromBoundary(0, pos.y);
}
if (pos.x > 1 - size)
{
pushAwayFromBoundary(1, pos.y);
}
if (pos.y < size)
{
pushAwayFromBoundary(pos.x, 0);
}
if (pos.y > 1 - size)
{
pushAwayFromBoundary(pos.x, 1);
}
//Always move repulsive zones away, no matter their distance
//TODO: Consider z plane?
for (auto& connection : zone.second->getConnections())
{
if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
{
auto & otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
float3 otherZoneCenter = otherZone->getCenter();
//TODO: Roll into lambda?
auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
float minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize;
float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
localForce *= (distancesBetweenZones[zone.second->getId()][otherZone->getId()]);
forceVector -= localForce * scaleForceBetweenZones(zone.second, otherZone);
}
}
overlaps[zone.second] = overlap;
forceVector.z = 0; //operator - doesn't preserve z coordinate :/
forces[zone.second] = forceVector;
}
}
void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
{
//The more zones, the greater total distance expected
//Also, higher stiffness make expected movement lower
const int maxDistanceMovementRatio = zones.size() * zones.size() * (stiffnessConstant / stifness);
typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
std::vector<Misplacement> misplacedZones;
float totalDistance = 0;
float totalOverlap = 0;
for (const auto& zone : distances) //find most misplaced zone
{
if (vstd::contains(lastSwappedZones, zone.first->getId()))
{
continue;
}
totalDistance += zone.second;
float overlap = overlaps[zone.first];
totalOverlap += overlap;
//if distance to actual movement is long, the zone is misplaced
float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
if (ratio > maxDistanceMovementRatio)
{
misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
}
}
if (misplacedZones.empty())
return;
boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
{
return lhs.first > rhs.first; //Largest displacement first
});
#ifdef ZONE_PLACEMENT_LOG
logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
#endif
if (misplacedZones.size() >= 2)
{
//Swap 2 misplaced zones
auto firstZone = misplacedZones.front().second;
std::shared_ptr<Zone> secondZone;
std::set<TRmgTemplateZoneId> connectedZones;
for (const auto& connection : firstZone->getConnections())
{
switch (connection.getConnectionType())
{
//Do not consider virtual connections for graph distance
case rmg::EConnectionType::REPULSIVE:
case rmg::EConnectionType::FORCE_PORTAL:
continue;
}
if (connection.getZoneA() == connection.getZoneB())
{
//Do not consider self-connections
continue;
}
connectedZones.insert(connection.getOtherZoneId(firstZone->getId()));
}
auto level = firstZone->getCenter().z;
for (size_t i = 1; i < misplacedZones.size(); i++)
{
//Only swap zones on the same level
//Don't swap zones that should be connected (Jebus)
if (misplacedZones[i].second->getCenter().z == level &&
!vstd::contains(connectedZones, misplacedZones[i].second->getId()))
{
secondZone = misplacedZones[i].second;
break;
}
}
if (secondZone)
{
#ifdef ZONE_PLACEMENT_LOG
logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
#endif
auto firstCenter = firstZone->getCenter();
auto secondCenter = secondZone->getCenter();
firstZone->setCenter(secondCenter);
secondZone->setCenter(firstCenter);
lastSwappedZones.insert(firstZone->getId());
lastSwappedZones.insert(secondZone->getId());
return;
}
}
lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
//find most distant zone that should be attracted and move inside it
std::shared_ptr<Zone> targetZone;
auto misplacedZone = misplacedZones.front().second;
float3 ourCenter = misplacedZone->getCenter();
if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
{
//Move one zone towards most distant zone to reduce distance
float maxDistance = 0;
for (const auto & con : misplacedZone->getConnections())
{
if (con.getConnectionType() == rmg::EConnectionType::REPULSIVE)
{
continue;
}
auto otherZone = zones[con.getOtherZoneId(misplacedZone->getId())];
float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
if (distance > maxDistance)
{
maxDistance = distance;
targetZone = otherZone;
}
}
if (targetZone)
{
float3 vec = targetZone->getCenter() - ourCenter;
float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
#ifdef ZONE_PLACEMENT_LOG
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());
#endif
misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
}
}
else
{
//Move misplaced zone away from overlapping zone
float maxOverlap = 0;
for(const auto & otherZone : zones)
{
float3 otherZoneCenter = otherZone.second->getCenter();
if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
continue;
auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
if (distance > maxOverlap)
{
maxOverlap = distance;
targetZone = otherZone.second;
}
}
if (targetZone)
{
float3 vec = ourCenter - targetZone->getCenter();
float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
#ifdef ZONE_PLACEMENT_LOG
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());
#endif
misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
}
}
//Don't swap that zone in next iteration
lastSwappedZones.insert(misplacedZone->getId());
}
float CZonePlacer::metric (const int3 &A, const int3 &B) const
{
return A.dist2dSQ(B);
}
void CZonePlacer::assignZones(vstd::RNG * rand)
{
logGlobal->info("Starting zone colouring");
auto width = map.getMapGenOptions().getWidth();
auto height = map.getMapGenOptions().getHeight();
auto zones = map.getZones();
vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
{
return pr.second->getType() == ETemplateZoneType::WATER;
});
using Dpair = std::pair<std::shared_ptr<Zone>, float>;
std::vector <Dpair> distances;
distances.reserve(zones.size());
//now place zones correctly and assign tiles to each zone
auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
{
//bigger zones have smaller distance
return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
};
auto simpleCompareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
{
//bigger zones have smaller distance
return lhs.second < rhs.second;
};
int levels = map.levels();
// Find current center of mass for each zone. Move zone to that center to balance zones sizes
std::vector<RmgMap::Zones> zonesOnLevel;
for(int level = 0; level < levels; level++)
{
zonesOnLevel.push_back(map.getZonesOnLevel(level));
}
int3 pos;
for(pos.z = 0; pos.z < levels; pos.z++)
{
for(pos.x = 0; pos.x < width; pos.x++)
{
for(pos.y = 0; pos.y < height; pos.y++)
{
distances.clear();
for(const auto & zone : zonesOnLevel[pos.z])
{
distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
}
boost::min_element(distances, compareByDistance)->first->area()->add(pos); //closest tile belongs to zone
}
}
}
for(const auto & zone : zones)
{
if(zone.second->area()->empty())
throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
zone.second->moveToCenterOfMass();
}
for(const auto & zone : zones)
zone.second->clearTiles(); //now populate them again
PenroseTiling penrose;
for (int level = 0; level < levels; level++)
{
//Create different tiling for each level
auto vertices = penrose.generatePenroseTiling(zonesOnLevel[level].size(), rand);
// Assign zones to closest Penrose vertex
std::map<std::shared_ptr<Zone>, std::set<int3>> vertexMapping;
for (const auto & vertex : vertices)
{
distances.clear();
for(const auto & zone : zonesOnLevel[level])
{
distances.emplace_back(zone.second, zone.second->getCenter().dist2dSQ(float3(vertex.x(), vertex.y(), level)));
}
auto closestZone = boost::min_element(distances, compareByDistance)->first;
vertexMapping[closestZone].insert(int3(vertex.x() * width, vertex.y() * height, level)); //Closest vertex belongs to zone
}
//Assign actual tiles to each zone
pos.z = level;
for (pos.x = 0; pos.x < width; pos.x++)
{
for (pos.y = 0; pos.y < height; pos.y++)
{
distances.clear();
for(const auto & zoneVertex : vertexMapping)
{
auto zone = zoneVertex.first;
for (const auto & vertex : zoneVertex.second)
{
distances.emplace_back(zone, metric(pos, vertex));
}
}
//Tile closest to vertex belongs to zone
auto closestZone = boost::min_element(distances, simpleCompareByDistance)->first;
closestZone->area()->add(pos);
map.setZoneID(pos, closestZone->getId());
}
}
for(const auto & zone : zonesOnLevel[level])
{
if(zone.second->area()->empty())
{
// FIXME: Some vertices are duplicated, but it's not a source of problem
logGlobal->error("Zone %d at %s is empty, dumping Penrose tiling", zone.second->getId(), zone.second->getCenter().toString());
for (const auto & vertex : vertices)
{
logGlobal->warn("Penrose Vertex: %s", vertex.toString());
}
throw rmgException("Empty zone after Penrose tiling");
}
}
}
//set position (town position) to center of mass of irregular zone
for(const auto & zone : zones)
{
zone.second->moveToCenterOfMass();
//TODO: similar for islands
#define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
if (zone.second->isUnderground())
{
if (!CREATE_FULL_UNDERGROUND)
{
auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
for(const auto & t : discardTiles)
zone.second->area()->erase(t);
}
//make sure that terrain inside zone is not a rock
auto v = zone.second->area()->getTilesVector();
map.getMapProxy()->drawTerrain(*rand, v, ETerrainId::SUBTERRANEAN);
}
}
logGlobal->info("Finished zone colouring");
}
void CZonePlacer::RemoveRoadsForWideConnections()
{
auto zones = map.getZones();
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getConnectionType() == rmg::EConnectionType::WIDE)
{
zonePtr.second->setRoadOption(connection.getId(), rmg::ERoadOption::ROAD_FALSE);
}
}
}
}
TRmgTemplateZoneId findSet(std::map<TRmgTemplateZoneId, TRmgTemplateZoneId> & parent, TRmgTemplateZoneId x)
{
if(parent[x] != x)
parent[x] = findSet(parent, parent[x]);
return parent[x];
}
void unionSets(std::map<TRmgTemplateZoneId, TRmgTemplateZoneId> & parent, TRmgTemplateZoneId x, TRmgTemplateZoneId y)
{
TRmgTemplateZoneId rx = findSet(parent, x);
TRmgTemplateZoneId ry = findSet(parent, y);
if(rx != ry)
parent[rx] = ry;
}
/*
Random road generation requirements:
- Every town should be connected via road
- There should be exactly one road betwen any two towns (connected MST)
- This excludes cases when there are multiple road connetions betwween two zones
- Road cannot end in a zone without town
- Wide connections should have no road
*/
void CZonePlacer::dropRandomRoads(vstd::RNG * rand)
{
logGlobal->info("Starting road randomization");
auto zones = map.getZones();
// Helper lambda to set road option for all instances of a connection
auto setRoadOptionForConnection = [&zones](int connectionId, rmg::ERoadOption roadOption)
{
// Update all instances of this connection (A→B and B→A) to have the same road option
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getId() == connectionId)
{
zonePtr.second->setRoadOption(connectionId, roadOption);
}
}
}
};
// Identify zones with towns
std::set<TRmgTemplateZoneId> zonesWithTowns;
for(const auto & zone : zones)
{
if(zone.second->getPlayerTowns().getTownCount() ||
zone.second->getPlayerTowns().getCastleCount() ||
zone.second->getNeutralTowns().getTownCount() ||
zone.second->getNeutralTowns().getCastleCount())
{
zonesWithTowns.insert(zone.first);
}
}
logGlobal->info("Found %d zones with towns", zonesWithTowns.size());
if(zonesWithTowns.empty())
{
// No towns, no roads needed - mark all RANDOM roads as FALSE
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM)
{
setRoadOptionForConnection(connection.getId(), rmg::ERoadOption::ROAD_FALSE);
}
}
}
return;
}
// Track direct connections between zones (both TRUE and RANDOM)
std::map<TRmgTemplateZoneId, std::map<TRmgTemplateZoneId, bool>> directConnections;
// First pass: find all TRUE connections
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
auto zoneA = connection.getZoneA();
auto zoneB = connection.getZoneB();
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_TRUE)
{
// Mark that these zones are directly connected by a TRUE road
directConnections[zoneA][zoneB] = true;
directConnections[zoneB][zoneA] = true;
}
}
}
// Track all available connections in the template (for graph connectivity analysis)
std::map<TRmgTemplateZoneId, std::set<TRmgTemplateZoneId>> allConnections;
std::map<std::pair<TRmgTemplateZoneId, TRmgTemplateZoneId>, int> connectionIds;
// Build adjacency list for available connections and track connection IDs
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
auto zoneA = connection.getZoneA();
auto zoneB = connection.getZoneB();
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_TRUE ||
connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM)
{
// Only include TRUE and RANDOM roads in connectivity analysis
allConnections[zoneA].insert(zoneB);
allConnections[zoneB].insert(zoneA);
// Track connection ID for later use
connectionIds[{std::min(zoneA, zoneB), std::max(zoneA, zoneB)}] = connection.getId();
}
}
}
// Check if there's a path between all town zones using all available connections
// This is to verify if global connectivity is even possible
std::map<TRmgTemplateZoneId, std::set<TRmgTemplateZoneId>> reachableTowns;
for(auto startTown : zonesWithTowns)
{
std::queue<TRmgTemplateZoneId> q;
std::set<TRmgTemplateZoneId> visited;
q.push(startTown);
visited.insert(startTown);
while(!q.empty())
{
auto current = q.front();
q.pop();
for(auto neighbor : allConnections[current])
{
if(!vstd::contains(visited, neighbor))
{
visited.insert(neighbor);
q.push(neighbor);
if(vstd::contains(zonesWithTowns, neighbor))
{
reachableTowns[startTown].insert(neighbor);
}
}
}
}
}
// Initialize Union-Find for MST tracking
std::map<TRmgTemplateZoneId, TRmgTemplateZoneId> parent;
for(auto townZone : zonesWithTowns)
{
parent[townZone] = townZone;
}
// Add all TRUE roads connecting town zones to MST
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_TRUE)
{
auto zoneA = connection.getZoneA();
auto zoneB = connection.getZoneB();
// If both zones have towns, add to MST
if(vstd::contains(zonesWithTowns, zoneA) && vstd::contains(zonesWithTowns, zoneB))
{
unionSets(parent, zoneA, zoneB);
}
}
}
}
// Process all paths through true roads (BFS)
for(auto townZone : zonesWithTowns)
{
std::queue<TRmgTemplateZoneId> q;
std::set<TRmgTemplateZoneId> visited;
q.push(townZone);
visited.insert(townZone);
while(!q.empty())
{
auto current = q.front();
q.pop();
for(auto & otherZone : directConnections[current])
{
if(otherZone.second && !vstd::contains(visited, otherZone.first))
{
visited.insert(otherZone.first);
q.push(otherZone.first);
// If this is another town, update MST
if(vstd::contains(zonesWithTowns, otherZone.first))
{
unionSets(parent, townZone, otherZone.first);
}
}
}
}
}
// Process RANDOM connections
// First, ensure each town has at least one connection
for(auto townZone : zonesWithTowns)
{
// Skip if already has a TRUE road
if(!directConnections[townZone].empty())
continue;
// Find a random connection to upgrade to TRUE
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM &&
(connection.getZoneA() == townZone || connection.getZoneB() == townZone))
{
auto zoneA = connection.getZoneA();
auto zoneB = connection.getZoneB();
// Don't upgrade if these zones are already directly connected by a TRUE road
if(vstd::contains(directConnections[zoneA], zoneB) && directConnections[zoneA][zoneB])
continue;
// Upgrade to TRUE
setRoadOptionForConnection(connection.getId(), rmg::ERoadOption::ROAD_TRUE);
directConnections[zoneA][zoneB] = true;
directConnections[zoneB][zoneA] = true;
auto otherZone = (zoneA == townZone) ? zoneB : zoneA;
logGlobal->info("Setting RANDOM road to TRUE for connection %d to ensure town zone %d has at least one connection (to zone %d)",
connection.getId(), townZone, otherZone);
break;
}
}
// Stop if we've found a connection
if(!directConnections[townZone].empty())
break;
}
}
// Process remaining RANDOM roads - prioritize town connectivity
// First collect all RANDOM roads
std::vector<std::pair<int, std::pair<TRmgTemplateZoneId, TRmgTemplateZoneId>>> randomRoads;
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM)
{
auto id = connection.getId();
auto zoneA = connection.getZoneA();
auto zoneB = connection.getZoneB();
// Skip if these zones are already directly connected by a TRUE road
if(vstd::contains(directConnections[zoneA], zoneB) && directConnections[zoneA][zoneB])
{
setRoadOptionForConnection(id, rmg::ERoadOption::ROAD_FALSE);
logGlobal->info("Setting RANDOM road to FALSE for connection %d - duplicate of TRUE road between zones %d and %d",
id, zoneA, zoneB);
continue;
}
randomRoads.push_back(std::make_pair(id, std::make_pair(zoneA, zoneB)));
}
}
}
RandomGeneratorUtil::randomShuffle(randomRoads, *rand);
// Process random roads - first connect town zones
for(auto& road : randomRoads)
{
auto id = road.first;
auto zoneA = road.second.first;
auto zoneB = road.second.second;
bool setToTrue = false;
// If both zones have towns, check if they're already connected in the MST
if(vstd::contains(zonesWithTowns, zoneA) && vstd::contains(zonesWithTowns, zoneB))
{
if(findSet(parent, zoneA) != findSet(parent, zoneB))
{
// Not connected, add this road to MST
unionSets(parent, zoneA, zoneB);
setToTrue = true;
logGlobal->info("Setting RANDOM road to TRUE for connection %d between town zones %d and %d",
id, zoneA, zoneB);
}
}
// If one zone has a town and one doesn't
else if(vstd::contains(zonesWithTowns, zoneA) || vstd::contains(zonesWithTowns, zoneB))
{
TRmgTemplateZoneId townZone = vstd::contains(zonesWithTowns, zoneA) ? zoneA : zoneB;
TRmgTemplateZoneId nonTownZone = vstd::contains(zonesWithTowns, zoneA) ? zoneB : zoneA;
// Check if this town already has at least one TRUE connection
if(directConnections[townZone].empty())
{
setToTrue = true;
logGlobal->info("Setting RANDOM road to TRUE for connection %d - only connection for town zone %d",
id, townZone);
}
else
{
// See if this non-town zone connects to another town zone
// This could be a potential bridge zone to connect towns
bool connectsToOtherTown = false;
TRmgTemplateZoneId otherTownZone = 0;
for(auto connectedZone : allConnections[nonTownZone])
{
if(vstd::contains(zonesWithTowns, connectedZone) && connectedZone != townZone)
{
otherTownZone = connectedZone;
connectsToOtherTown = true;
break;
}
}
if(connectsToOtherTown && findSet(parent, townZone) != findSet(parent, otherTownZone))
{
// This non-town zone can help connect two town zones that are not yet connected
setToTrue = true;
logGlobal->info("Setting RANDOM road to TRUE for connection %d - bridge through non-town zone %d to connect towns %d and %d",
id, nonTownZone, townZone, otherTownZone);
}
}
}
// Update all zones with this connection
setRoadOptionForConnection(id, setToTrue ? rmg::ERoadOption::ROAD_TRUE : rmg::ERoadOption::ROAD_FALSE);
if(setToTrue)
{
directConnections[zoneA][zoneB] = true;
directConnections[zoneB][zoneA] = true;
}
}
// Check if we have a connected graph for town zones after initial MST
std::map<TRmgTemplateZoneId, std::set<TRmgTemplateZoneId>> connectedComponents;
std::set<TRmgTemplateZoneId> processedTowns;
for(auto townZone : zonesWithTowns)
{
if(vstd::contains(processedTowns, townZone))
continue;
std::set<TRmgTemplateZoneId> component;
for(auto otherTown : zonesWithTowns)
{
if(findSet(parent, townZone) == findSet(parent, otherTown))
{
component.insert(otherTown);
processedTowns.insert(otherTown);
}
}
if(!component.empty())
connectedComponents[townZone] = component;
}
// If we have more than one component, try to connect them if possible
if(connectedComponents.size() > 1)
{
logGlobal->warn("Found %d disconnected town components, trying to connect them", connectedComponents.size());
// Create a list of components
std::vector<std::set<TRmgTemplateZoneId>> components;
for(auto & component : connectedComponents)
{
components.push_back(component.second);
}
// For each pair of components, try to find a path between them
for(size_t i = 0; i < components.size() - 1; i++)
{
bool foundBridge = false;
for(size_t j = i + 1; j < components.size() && !foundBridge; j++)
{
// Try to find a path between any two towns in different components
for(auto townA : components[i])
{
if(foundBridge) break;
for(auto townB : components[j])
{
// Check if there's a path between townA and townB in the original template
if(vstd::contains(reachableTowns[townA], townB))
{
// There's a path, now find the specific path to enable roads on
std::queue<TRmgTemplateZoneId> q;
std::map<TRmgTemplateZoneId, TRmgTemplateZoneId> prev;
q.push(townA);
prev[townA] = 0; // Mark as visited with no predecessor
bool found = false;
while(!q.empty() && !found)
{
auto current = q.front();
q.pop();
for(auto next : allConnections[current])
{
if(!vstd::contains(prev, next))
{
prev[next] = current;
q.push(next);
if(next == townB)
{
found = true;
break;
}
}
}
}
// Now reconstruct the path and set all roads on this path to TRUE
if(found)
{
std::vector<TRmgTemplateZoneId> path;
TRmgTemplateZoneId current = townB;
while(current != townA)
{
path.push_back(current);
current = prev[current];
}
path.push_back(townA);
// Reverse to get path from townA to townB
std::reverse(path.begin(), path.end());
logGlobal->info("Found path between town zones %d and %d, enabling all roads on this path", townA, townB);
// Enable all roads on this path
for(size_t k = 0; k < path.size() - 1; k++)
{
auto zoneA = path[k];
auto zoneB = path[k+1];
auto minZone = std::min(zoneA, zoneB);
auto maxZone = std::max(zoneA, zoneB);
if(vstd::contains(connectionIds, std::make_pair(minZone, maxZone)))
{
auto connectionId = connectionIds[std::make_pair(minZone, maxZone)];
// Enable this road if it's not already TRUE
for(auto & zonePtr : zones)
{
for(auto & connection : zonePtr.second->getConnections())
{
if(connection.getId() == connectionId &&
connection.getRoadOption() == rmg::ERoadOption::ROAD_RANDOM)
{
setRoadOptionForConnection(connectionId, rmg::ERoadOption::ROAD_TRUE);
directConnections[zoneA][zoneB] = true;
directConnections[zoneB][zoneA] = true;
logGlobal->info("Setting RANDOM road to TRUE for connection %d to connect components - part of path between towns %d and %d",
connectionId, townA, townB);
break;
}
}
}
}
}
// Update Union-Find to merge components
unionSets(parent, townA, townB);
foundBridge = true;
break;
}
}
}
}
}
if(!foundBridge)
{
logGlobal->warn("Could not find a path between component with towns [%s] and other components",
[&components, i]() {
std::string result;
for(auto town : components[i])
{
if(!result.empty()) result += ", ";
result += std::to_string(town);
}
return result;
}().c_str());
}
}
}
// Final check for connectivity between town zones
std::set<TRmgTemplateZoneId> connectedTowns;
if(!zonesWithTowns.empty())
{
auto firstTown = *zonesWithTowns.begin();
for(auto town : zonesWithTowns)
{
if(findSet(parent, firstTown) == findSet(parent, town))
{
connectedTowns.insert(town);
}
}
}
logGlobal->info("Final town connectivity: %d connected out of %d total town zones",
connectedTowns.size(), zonesWithTowns.size());
logGlobal->info("Finished road generation - created minimal spanning tree connecting all towns");
}
const TDistanceMap& CZonePlacer::getDistanceMap()
{
return distancesBetweenZones;
}
VCMI_LIB_NAMESPACE_END