CMapGenerator.cpp 12 KB

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