CMapGenerator.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #include "StdInc.h"
  2. #include "CMapGenerator.h"
  3. #include "../mapping/CMap.h"
  4. #include "../VCMI_Lib.h"
  5. #include "../CGeneralTextHandler.h"
  6. #include "../mapping/CMapEditManager.h"
  7. #include "../CTownHandler.h"
  8. #include "../StringConstants.h"
  9. #include "../filesystem/Filesystem.h"
  10. #include "CRmgTemplate.h"
  11. #include "CRmgTemplateZone.h"
  12. #include "CZonePlacer.h"
  13. #include "../mapObjects/CObjectClassesHandler.h"
  14. void CMapGenerator::foreach_neighbour(const int3 &pos, std::function<void(int3& pos)> foo)
  15. {
  16. for(const int3 &dir : dirs)
  17. {
  18. int3 n = pos + dir;
  19. if(map->isInTheMap(n))
  20. foo(n);
  21. }
  22. }
  23. CMapGenerator::CMapGenerator(shared_ptr<CMapGenOptions> mapGenOptions, int RandomSeed /*= std::time(nullptr)*/) :
  24. mapGenOptions(mapGenOptions), randomSeed(RandomSeed), monolithIndex(0), zonesTotal(0)
  25. {
  26. rand.setSeed(randomSeed);
  27. }
  28. void CMapGenerator::initTiles()
  29. {
  30. map->initTerrain();
  31. int width = map->width;
  32. int height = map->height;
  33. int level = map->twoLevel ? 2 : 1;
  34. tiles = new CTileInfo**[width];
  35. for (int i = 0; i < width; ++i)
  36. {
  37. tiles[i] = new CTileInfo*[height];
  38. for (int j = 0; j < height; ++j)
  39. {
  40. tiles[i][j] = new CTileInfo[level];
  41. }
  42. }
  43. }
  44. CMapGenerator::~CMapGenerator()
  45. {
  46. if (tiles)
  47. {
  48. int width = mapGenOptions->getWidth();
  49. int height = mapGenOptions->getHeight();
  50. for (int i=0; i < width; i++)
  51. {
  52. for(int j=0; j < height; j++)
  53. {
  54. delete [] tiles[i][j];
  55. }
  56. delete [] tiles[i];
  57. }
  58. delete [] tiles;
  59. }
  60. }
  61. std::unique_ptr<CMap> CMapGenerator::generate()
  62. {
  63. mapGenOptions->finalize(rand);
  64. map = make_unique<CMap>();
  65. editManager = map->getEditManager();
  66. try
  67. {
  68. editManager->getUndoManager().setUndoRedoLimit(0);
  69. addHeaderInfo();
  70. initTiles();
  71. genZones();
  72. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  73. fillZones();
  74. //updated fuarded tiles will be calculated in CGameState::initMapObjects()
  75. }
  76. catch (rmgException &e)
  77. {
  78. logGlobal->errorStream() << "Random map generation received exception: " << e.what();
  79. }
  80. return std::move(map);
  81. }
  82. std::string CMapGenerator::getMapDescription() const
  83. {
  84. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  85. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  86. std::stringstream ss;
  87. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  88. ", levels %s, humans %d, computers %d, water %s, monster %s, second expansion map") % mapGenOptions->getMapTemplate()->getName() %
  89. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  90. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  91. monsterStrengthStr[mapGenOptions->getMonsterStrength()]);
  92. for(const auto & pair : mapGenOptions->getPlayersSettings())
  93. {
  94. const auto & pSettings = pair.second;
  95. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  96. {
  97. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  98. }
  99. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  100. {
  101. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  102. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  103. }
  104. }
  105. return ss.str();
  106. }
  107. void CMapGenerator::addPlayerInfo()
  108. {
  109. // Calculate which team numbers exist
  110. std::array<std::list<int>, 2> teamNumbers; // 0= cpu/human, 1= cpu only
  111. int teamOffset = 0;
  112. for(int i = 0; i < 2; ++i)
  113. {
  114. int playerCount = i == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getCompOnlyPlayerCount();
  115. int teamCount = i == 0 ? mapGenOptions->getTeamCount() : mapGenOptions->getCompOnlyTeamCount();
  116. if(playerCount == 0)
  117. {
  118. continue;
  119. }
  120. int playersPerTeam = playerCount /
  121. (teamCount == 0 ? playerCount : teamCount);
  122. int teamCountNorm = teamCount;
  123. if(teamCountNorm == 0)
  124. {
  125. teamCountNorm = playerCount;
  126. }
  127. for(int j = 0; j < teamCountNorm; ++j)
  128. {
  129. for(int k = 0; k < playersPerTeam; ++k)
  130. {
  131. teamNumbers[i].push_back(j + teamOffset);
  132. }
  133. }
  134. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  135. {
  136. teamNumbers[i].push_back(j + teamOffset);
  137. }
  138. teamOffset += teamCountNorm;
  139. }
  140. // Team numbers are assigned randomly to every player
  141. for(const auto & pair : mapGenOptions->getPlayersSettings())
  142. {
  143. const auto & pSettings = pair.second;
  144. PlayerInfo player;
  145. player.canComputerPlay = true;
  146. int j = pSettings.getPlayerType() == EPlayerType::COMP_ONLY ? 1 : 0;
  147. if(j == 0)
  148. {
  149. player.canHumanPlay = true;
  150. }
  151. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  152. player.team = TeamID(*itTeam);
  153. teamNumbers[j].erase(itTeam);
  154. map->players[pSettings.getColor().getNum()] = player;
  155. }
  156. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  157. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  158. }
  159. void CMapGenerator::genZones()
  160. {
  161. editManager->clearTerrain(&rand);
  162. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  163. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  164. auto pcnt = mapGenOptions->getPlayerCount();
  165. auto w = mapGenOptions->getWidth();
  166. auto h = mapGenOptions->getHeight();
  167. auto tmpl = mapGenOptions->getMapTemplate();
  168. zones = tmpl->getZones(); //copy from template (refactor?)
  169. int player_per_side = zones.size() > 4 ? 3 : 2;
  170. logGlobal->infoStream() << boost::format("Map size %d %d, players per side %d") % w % h % player_per_side;
  171. CZonePlacer placer(this);
  172. placer.placeZones(mapGenOptions, &rand);
  173. placer.assignZones(mapGenOptions);
  174. int i = 0;
  175. for(auto const it : zones)
  176. {
  177. CRmgTemplateZone * zone = it.second;
  178. zone->setType(i < pcnt ? ETemplateZoneType::PLAYER_START : ETemplateZoneType::TREASURE);
  179. this->zones[it.first] = zone;
  180. ++i;
  181. }
  182. logGlobal->infoStream() << "Zones generated successfully";
  183. }
  184. void CMapGenerator::fillZones()
  185. {
  186. logGlobal->infoStream() << "Started filling zones";
  187. createConnections();
  188. //make sure all connections are passable before creating borders
  189. for (auto it : zones)
  190. {
  191. it.second->createBorder(this);
  192. it.second->fill(this);
  193. }
  194. logGlobal->infoStream() << "Zones filled successfully";
  195. }
  196. void CMapGenerator::createConnections()
  197. {
  198. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  199. {
  200. auto zoneA = connection.getZoneA();
  201. auto zoneB = connection.getZoneB();
  202. //rearrange tiles in random order
  203. auto tilesCopy = zoneA->getTileInfo();
  204. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  205. RandomGeneratorUtil::randomShuffle(tiles, rand);
  206. int3 guardPos(-1,-1,-1);
  207. auto otherZoneTiles = zoneB->getTileInfo();
  208. int3 posA = zoneA->getPos();
  209. int3 posB = zoneB->getPos();
  210. if (posA.z == posB.z)
  211. {
  212. for (auto tile : tiles)
  213. {
  214. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  215. continue;
  216. foreach_neighbour (tile, [&guardPos, tile, &otherZoneTiles, this](int3 &pos)
  217. {
  218. //if (vstd::contains(otherZoneTiles, pos) && !this->isBlocked(pos))
  219. if (vstd::contains(otherZoneTiles, pos))
  220. guardPos = tile;
  221. });
  222. if (guardPos.valid())
  223. {
  224. setOccupied (guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  225. zoneA->addMonster (this, guardPos, connection.getGuardStrength());
  226. //zones can make paths only in their own area
  227. zoneA->crunchPath (this, guardPos, posA, zoneA->getId(), zoneA->getFreePaths()); //make connection towards our zone center
  228. zoneB->crunchPath (this, guardPos, posB, zoneB->getId(), zoneB->getFreePaths()); //make connection towards other zone center
  229. break; //we're done with this connection
  230. }
  231. }
  232. }
  233. else //create subterranean gates between two zones
  234. {
  235. //find point on the path between zones
  236. float3 offset (posB.x - posA.x, posB.y - posA.y, 0);
  237. float distance = posB.dist2d(posA);
  238. vstd::amax (distance, 0.5f);
  239. offset /= distance; //get unit vector
  240. float3 vec (0, 0, 0);
  241. //use reduced size of underground zone - make sure gate does not stand on rock
  242. int3 tile = posA;
  243. int3 otherTile = tile;
  244. bool stop = false;
  245. while (!stop)
  246. {
  247. vec += offset; //this vector may extend beyond line between zone centers, in case they are directly over each other
  248. tile = posA + int3(vec.x, vec.y, 0);
  249. float distanceFromA = posA.dist2d(tile);
  250. float distanceFromB = posB.dist2d(tile);
  251. if (distanceFromA + distanceFromB > std::max<int>(zoneA->getSize() + zoneB->getSize(), distance))
  252. break; //we are too far away to ever connect
  253. //if zone is underground, gate must fit within its (reduced) radius
  254. if (distanceFromA > 5 && (!posA.z || distanceFromA < zoneA->getSize() - 3) &&
  255. distanceFromB > 5 && (!posB.z || distanceFromB < zoneB->getSize() - 3))
  256. {
  257. otherTile = tile;
  258. otherTile.z = posB.z;
  259. if (vstd::contains(tiles, tile) && vstd::contains(otherZoneTiles, otherTile))
  260. {
  261. bool withinZone = true;
  262. foreach_neighbour (tile, [&withinZone, &tiles](int3 &pos)
  263. {
  264. if (!vstd::contains(tiles, pos))
  265. withinZone = false;
  266. });
  267. foreach_neighbour (otherTile, [&withinZone, &otherZoneTiles](int3 &pos)
  268. {
  269. if (!vstd::contains(otherZoneTiles, pos))
  270. withinZone = false;
  271. });
  272. if (withinZone)
  273. {
  274. auto gate1 = new CGTeleport;
  275. gate1->ID = Obj::SUBTERRANEAN_GATE;
  276. gate1->subID = 0;
  277. zoneA->placeAndGuardObject(this, gate1, tile, connection.getGuardStrength());
  278. auto gate2 = new CGTeleport(*gate1);
  279. zoneB->placeAndGuardObject(this, gate2, otherTile, connection.getGuardStrength());
  280. stop = true; //we are done, go to next connection
  281. }
  282. }
  283. }
  284. }
  285. if (stop)
  286. continue;
  287. }
  288. if (!guardPos.valid())
  289. {
  290. auto teleport1 = new CGTeleport;
  291. teleport1->ID = Obj::MONOLITH_TWO_WAY;
  292. teleport1->subID = getNextMonlithIndex();
  293. auto teleport2 = new CGTeleport(*teleport1);
  294. zoneA->addRequiredObject (teleport1, connection.getGuardStrength());
  295. zoneB->addRequiredObject (teleport2, connection.getGuardStrength());
  296. }
  297. }
  298. }
  299. void CMapGenerator::addHeaderInfo()
  300. {
  301. map->version = EMapFormat::SOD;
  302. map->width = mapGenOptions->getWidth();
  303. map->height = mapGenOptions->getHeight();
  304. map->twoLevel = mapGenOptions->getHasTwoLevels();
  305. map->name = VLC->generaltexth->allTexts[740];
  306. map->description = getMapDescription();
  307. map->difficulty = 1;
  308. addPlayerInfo();
  309. }
  310. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  311. {
  312. return zones;
  313. }
  314. bool CMapGenerator::isBlocked(const int3 &tile) const
  315. {
  316. if (!map->isInTheMap(tile))
  317. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  318. return tiles[tile.x][tile.y][tile.z].isBlocked();
  319. }
  320. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  321. {
  322. if (!map->isInTheMap(tile))
  323. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  324. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  325. }
  326. bool CMapGenerator::isPossible(const int3 &tile) const
  327. {
  328. if (!map->isInTheMap(tile))
  329. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  330. return tiles[tile.x][tile.y][tile.z].isPossible();
  331. }
  332. bool CMapGenerator::isFree(const int3 &tile) const
  333. {
  334. if (!map->isInTheMap(tile))
  335. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  336. return tiles[tile.x][tile.y][tile.z].isFree();
  337. }
  338. bool CMapGenerator::isUsed(const int3 &tile) const
  339. {
  340. if (!map->isInTheMap(tile))
  341. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  342. return tiles[tile.x][tile.y][tile.z].isUsed();
  343. }
  344. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  345. {
  346. if (!map->isInTheMap(tile))
  347. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  348. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  349. }
  350. CTileInfo CMapGenerator::getTile(const int3& tile) const
  351. {
  352. if (!map->isInTheMap(tile))
  353. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  354. return tiles[tile.x][tile.y][tile.z];
  355. }
  356. void CMapGenerator::setNearestObjectDistance(int3 &tile, int value)
  357. {
  358. if (!map->isInTheMap(tile))
  359. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  360. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  361. }
  362. int CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  363. {
  364. if (!map->isInTheMap(tile))
  365. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  366. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  367. }
  368. int CMapGenerator::getNextMonlithIndex()
  369. {
  370. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  371. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  372. else
  373. return monolithIndex++;
  374. }
  375. void CMapGenerator::registerZone (TFaction faction)
  376. {
  377. zonesPerFaction[faction]++;
  378. zonesTotal++;
  379. }
  380. ui32 CMapGenerator::getZoneCount(TFaction faction)
  381. {
  382. return zonesPerFaction[faction];
  383. }
  384. ui32 CMapGenerator::getTotalZoneCount() const
  385. {
  386. return zonesTotal;
  387. }