CMapGenerator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. //FIXME: what if map is not present anymore?
  46. if (tiles && map)
  47. {
  48. for (int i=0; i < map->width; i++)
  49. {
  50. for(int j=0; j < map->height; j++)
  51. {
  52. delete [] tiles[i][j];
  53. }
  54. delete [] tiles[i];
  55. }
  56. delete [] tiles;
  57. }
  58. }
  59. std::unique_ptr<CMap> CMapGenerator::generate()
  60. {
  61. mapGenOptions->finalize(rand);
  62. map = make_unique<CMap>();
  63. editManager = map->getEditManager();
  64. try
  65. {
  66. editManager->getUndoManager().setUndoRedoLimit(0);
  67. addHeaderInfo();
  68. initTiles();
  69. genZones();
  70. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  71. fillZones();
  72. }
  73. catch (rmgException &e)
  74. {
  75. logGlobal->errorStream() << "Random map generation received exception: " << e.what();
  76. }
  77. return std::move(map);
  78. }
  79. std::string CMapGenerator::getMapDescription() const
  80. {
  81. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  82. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  83. std::stringstream ss;
  84. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  85. ", levels %s, humans %d, computers %d, water %s, monster %s, second expansion map") % mapGenOptions->getMapTemplate()->getName() %
  86. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  87. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  88. monsterStrengthStr[mapGenOptions->getMonsterStrength()]);
  89. for(const auto & pair : mapGenOptions->getPlayersSettings())
  90. {
  91. const auto & pSettings = pair.second;
  92. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  93. {
  94. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  95. }
  96. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  97. {
  98. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  99. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  100. }
  101. }
  102. return ss.str();
  103. }
  104. void CMapGenerator::addPlayerInfo()
  105. {
  106. // Calculate which team numbers exist
  107. std::array<std::list<int>, 2> teamNumbers; // 0= cpu/human, 1= cpu only
  108. int teamOffset = 0;
  109. for(int i = 0; i < 2; ++i)
  110. {
  111. int playerCount = i == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getCompOnlyPlayerCount();
  112. int teamCount = i == 0 ? mapGenOptions->getTeamCount() : mapGenOptions->getCompOnlyTeamCount();
  113. if(playerCount == 0)
  114. {
  115. continue;
  116. }
  117. int playersPerTeam = playerCount /
  118. (teamCount == 0 ? playerCount : teamCount);
  119. int teamCountNorm = teamCount;
  120. if(teamCountNorm == 0)
  121. {
  122. teamCountNorm = playerCount;
  123. }
  124. for(int j = 0; j < teamCountNorm; ++j)
  125. {
  126. for(int k = 0; k < playersPerTeam; ++k)
  127. {
  128. teamNumbers[i].push_back(j + teamOffset);
  129. }
  130. }
  131. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  132. {
  133. teamNumbers[i].push_back(j + teamOffset);
  134. }
  135. teamOffset += teamCountNorm;
  136. }
  137. // Team numbers are assigned randomly to every player
  138. for(const auto & pair : mapGenOptions->getPlayersSettings())
  139. {
  140. const auto & pSettings = pair.second;
  141. PlayerInfo player;
  142. player.canComputerPlay = true;
  143. int j = pSettings.getPlayerType() == EPlayerType::COMP_ONLY ? 1 : 0;
  144. if(j == 0)
  145. {
  146. player.canHumanPlay = true;
  147. }
  148. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  149. player.team = TeamID(*itTeam);
  150. teamNumbers[j].erase(itTeam);
  151. map->players[pSettings.getColor().getNum()] = player;
  152. }
  153. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  154. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  155. }
  156. void CMapGenerator::genZones()
  157. {
  158. editManager->clearTerrain(&rand);
  159. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  160. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  161. auto pcnt = mapGenOptions->getPlayerCount();
  162. auto w = mapGenOptions->getWidth();
  163. auto h = mapGenOptions->getHeight();
  164. auto tmpl = mapGenOptions->getMapTemplate();
  165. zones = tmpl->getZones(); //copy from template (refactor?)
  166. int player_per_side = zones.size() > 4 ? 3 : 2;
  167. logGlobal->infoStream() << boost::format("Map size %d %d, players per side %d") % w % h % player_per_side;
  168. CZonePlacer placer(this);
  169. placer.placeZones(mapGenOptions, &rand);
  170. placer.assignZones(mapGenOptions);
  171. int i = 0;
  172. for(auto const it : zones)
  173. {
  174. CRmgTemplateZone * zone = it.second;
  175. zone->setType(i < pcnt ? ETemplateZoneType::PLAYER_START : ETemplateZoneType::TREASURE);
  176. this->zones[it.first] = zone;
  177. ++i;
  178. }
  179. logGlobal->infoStream() << "Zones generated successfully";
  180. }
  181. void CMapGenerator::fillZones()
  182. {
  183. logGlobal->infoStream() << "Started filling zones";
  184. createConnections();
  185. for (auto it : zones)
  186. {
  187. //make sure all connections are passable before creating borders
  188. it.second->createBorder(this);
  189. it.second->fill(this);
  190. }
  191. logGlobal->infoStream() << "Zones filled successfully";
  192. }
  193. void CMapGenerator::createConnections()
  194. {
  195. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  196. {
  197. auto zoneA = connection.getZoneA();
  198. auto zoneB = connection.getZoneB();
  199. //rearrange tiles in random order
  200. auto tilesCopy = zoneA->getTileInfo();
  201. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  202. RandomGeneratorUtil::randomShuffle(tiles, rand);
  203. int3 guardPos(-1,-1,-1);
  204. auto otherZoneTiles = zoneB->getTileInfo();
  205. //auto otherZoneCenter = zoneB->getPos();
  206. for (auto tile : tiles)
  207. {
  208. foreach_neighbour (tile, [&guardPos, tile, &otherZoneTiles](int3 &pos)
  209. {
  210. if (vstd::contains(otherZoneTiles, pos))
  211. guardPos = tile;
  212. });
  213. if (guardPos.valid())
  214. {
  215. setOccupied (guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  216. zoneA->addMonster (this, guardPos, connection.getGuardStrength()); //TODO: set value according to template
  217. //zones can make paths only in their own area
  218. zoneA->crunchPath (this, guardPos, zoneA->getPos(), zoneA->getId()); //make connection towards our zone center
  219. zoneB->crunchPath (this, guardPos, zoneB->getPos(), zoneB->getId()); //make connection towards other zone center
  220. break; //we're done with this connection
  221. }
  222. }
  223. if (!guardPos.valid())
  224. {
  225. auto teleport1 = new CGTeleport;
  226. teleport1->ID = Obj::MONOLITH_TWO_WAY;
  227. teleport1->subID = getNextMonlithIndex();
  228. auto teleport2 = new CGTeleport(*teleport1);
  229. zoneA->addRequiredObject (teleport1, connection.getGuardStrength());
  230. zoneB->addRequiredObject (teleport2, connection.getGuardStrength());
  231. }
  232. }
  233. }
  234. void CMapGenerator::addHeaderInfo()
  235. {
  236. map->version = EMapFormat::SOD;
  237. map->width = mapGenOptions->getWidth();
  238. map->height = mapGenOptions->getHeight();
  239. map->twoLevel = mapGenOptions->getHasTwoLevels();
  240. map->name = VLC->generaltexth->allTexts[740];
  241. map->description = getMapDescription();
  242. map->difficulty = 1;
  243. addPlayerInfo();
  244. }
  245. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  246. {
  247. return zones;
  248. }
  249. bool CMapGenerator::isBlocked(const int3 &tile) const
  250. {
  251. if (!map->isInTheMap(tile))
  252. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  253. return tiles[tile.x][tile.y][tile.z].isBlocked();
  254. }
  255. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  256. {
  257. if (!map->isInTheMap(tile))
  258. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  259. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  260. }
  261. bool CMapGenerator::isPossible(const int3 &tile) const
  262. {
  263. if (!map->isInTheMap(tile))
  264. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  265. return tiles[tile.x][tile.y][tile.z].isPossible();
  266. }
  267. bool CMapGenerator::isFree(const int3 &tile) const
  268. {
  269. if (!map->isInTheMap(tile))
  270. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  271. return tiles[tile.x][tile.y][tile.z].isFree();
  272. }
  273. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  274. {
  275. if (!map->isInTheMap(tile))
  276. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  277. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  278. }
  279. CTileInfo CMapGenerator::getTile(const int3& tile) const
  280. {
  281. if (!map->isInTheMap(tile))
  282. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  283. return tiles[tile.x][tile.y][tile.z];
  284. }
  285. void CMapGenerator::setNearestObjectDistance(int3 &tile, int value)
  286. {
  287. if (!map->isInTheMap(tile))
  288. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  289. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  290. }
  291. int CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  292. {
  293. if (!map->isInTheMap(tile))
  294. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  295. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  296. }
  297. int CMapGenerator::getNextMonlithIndex()
  298. {
  299. return monolithIndex++;
  300. }