CMapGenerator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * CMapGenerator.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 "CMapGenerator.h"
  12. #include "../mapping/CMap.h"
  13. #include "../VCMI_Lib.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../mapping/CMapEditManager.h"
  16. #include "../CTownHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "CZonePlacer.h"
  20. #include "../mapObjects/CObjectClassesHandler.h"
  21. #include "TileInfo.h"
  22. #include "Zone.h"
  23. #include "Functions.h"
  24. #include "RmgMap.h"
  25. #include "ObjectManager.h"
  26. #include "TreasurePlacer.h"
  27. #include "RoadPlacer.h"
  28. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, int RandomSeed) :
  29. mapGenOptions(mapGenOptions), randomSeed(RandomSeed),
  30. prisonsRemaining(0), monolithIndex(0)
  31. {
  32. loadConfig();
  33. rand.setSeed(this->randomSeed);
  34. mapGenOptions.finalize(rand);
  35. map = std::make_unique<RmgMap>(mapGenOptions);
  36. }
  37. int CMapGenerator::getRandomSeed() const
  38. {
  39. return randomSeed;
  40. }
  41. void CMapGenerator::loadConfig()
  42. {
  43. static const ResourceID path("config/randomMap.json");
  44. JsonNode randomMapJson(path);
  45. for(auto& s : randomMapJson["terrain"]["undergroundAllow"].Vector())
  46. {
  47. if(!s.isNull())
  48. config.terrainUndergroundAllowed.emplace_back(s.String());
  49. }
  50. for(auto& s : randomMapJson["terrain"]["groundProhibit"].Vector())
  51. {
  52. if(!s.isNull())
  53. config.terrainGroundProhibit.emplace_back(s.String());
  54. }
  55. config.shipyardGuard = randomMapJson["waterZone"]["shipyard"]["value"].Integer();
  56. for(auto & treasure : randomMapJson["waterZone"]["treasure"].Vector())
  57. {
  58. config.waterTreasure.emplace_back(treasure["min"].Integer(), treasure["max"].Integer(), treasure["density"].Integer());
  59. }
  60. config.mineExtraResources = randomMapJson["mines"]["extraResourcesLimit"].Integer();
  61. config.minGuardStrength = randomMapJson["minGuardStrength"].Integer();
  62. config.defaultRoadType = randomMapJson["defaultRoadType"].String();
  63. config.secondaryRoadType = randomMapJson["secondaryRoadType"].String();
  64. config.treasureValueLimit = randomMapJson["treasureValueLimit"].Integer();
  65. for(auto & i : randomMapJson["prisons"]["experience"].Vector())
  66. config.prisonExperience.push_back(i.Integer());
  67. for(auto & i : randomMapJson["prisons"]["value"].Vector())
  68. config.prisonValues.push_back(i.Integer());
  69. for(auto & i : randomMapJson["scrolls"]["value"].Vector())
  70. config.scrollValues.push_back(i.Integer());
  71. for(auto & i : randomMapJson["pandoras"]["creaturesValue"].Vector())
  72. config.pandoraCreatureValues.push_back(i.Integer());
  73. for(auto & i : randomMapJson["quests"]["value"].Vector())
  74. config.questValues.push_back(i.Integer());
  75. for(auto & i : randomMapJson["quests"]["rewardValue"].Vector())
  76. config.questRewardValues.push_back(i.Integer());
  77. config.pandoraMultiplierGold = randomMapJson["pandoras"]["valueMultiplierGold"].Integer();
  78. config.pandoraMultiplierExperience = randomMapJson["pandoras"]["valueMultiplierExperience"].Integer();
  79. config.pandoraMultiplierSpells = randomMapJson["pandoras"]["valueMultiplierSpells"].Integer();
  80. config.pandoraSpellSchool = randomMapJson["pandoras"]["valueSpellSchool"].Integer();
  81. config.pandoraSpell60 = randomMapJson["pandoras"]["valueSpell60"].Integer();
  82. }
  83. const CMapGenerator::Config & CMapGenerator::getConfig() const
  84. {
  85. return config;
  86. }
  87. CMapGenerator::~CMapGenerator()
  88. {
  89. }
  90. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  91. {
  92. return mapGenOptions;
  93. }
  94. void CMapGenerator::initPrisonsRemaining()
  95. {
  96. prisonsRemaining = 0;
  97. for (auto isAllowed : map->map().allowedHeroes)
  98. {
  99. if (isAllowed)
  100. prisonsRemaining++;
  101. }
  102. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player
  103. }
  104. void CMapGenerator::initQuestArtsRemaining()
  105. {
  106. for (auto art : VLC->arth->objects)
  107. {
  108. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->id) && art->constituentOf.empty()) //don't use parts of combined artifacts
  109. questArtifacts.push_back(art->id);
  110. }
  111. }
  112. std::unique_ptr<CMap> CMapGenerator::generate()
  113. {
  114. try
  115. {
  116. addHeaderInfo();
  117. map->initTiles(*this);
  118. initPrisonsRemaining();
  119. initQuestArtsRemaining();
  120. genZones();
  121. map->map().calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  122. map->addModificators();
  123. fillZones();
  124. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  125. map->getZones().clear();
  126. }
  127. catch (rmgException &e)
  128. {
  129. logGlobal->error("Random map generation received exception: %s", e.what());
  130. }
  131. return std::move(map->mapInstance);
  132. }
  133. std::string CMapGenerator::getMapDescription() const
  134. {
  135. assert(map);
  136. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  137. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  138. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  139. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  140. if(!mapTemplate)
  141. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  142. std::stringstream ss;
  143. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  144. ", levels %s, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  145. randomSeed % map->map().width % map->map().height % (map->map().twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions.getPlayerCount()) %
  146. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  147. monsterStrengthStr[monsterStrengthIndex]);
  148. for(const auto & pair : mapGenOptions.getPlayersSettings())
  149. {
  150. const auto & pSettings = pair.second;
  151. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  152. {
  153. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  154. }
  155. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  156. {
  157. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  158. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->name;
  159. }
  160. }
  161. return ss.str();
  162. }
  163. void CMapGenerator::addPlayerInfo()
  164. {
  165. // Calculate which team numbers exist
  166. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  167. std::array<std::list<int>, 2> teamNumbers;
  168. int teamOffset = 0;
  169. int playerCount = 0;
  170. int teamCount = 0;
  171. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  172. {
  173. if (i == CPHUMAN)
  174. {
  175. playerCount = mapGenOptions.getPlayerCount();
  176. teamCount = mapGenOptions.getTeamCount();
  177. }
  178. else
  179. {
  180. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  181. teamCount = mapGenOptions.getCompOnlyTeamCount();
  182. }
  183. if(playerCount == 0)
  184. {
  185. continue;
  186. }
  187. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  188. int teamCountNorm = teamCount;
  189. if(teamCountNorm == 0)
  190. {
  191. teamCountNorm = playerCount;
  192. }
  193. for(int j = 0; j < teamCountNorm; ++j)
  194. {
  195. for(int k = 0; k < playersPerTeam; ++k)
  196. {
  197. teamNumbers[i].push_back(j + teamOffset);
  198. }
  199. }
  200. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  201. {
  202. teamNumbers[i].push_back(j + teamOffset);
  203. }
  204. teamOffset += teamCountNorm;
  205. }
  206. // Team numbers are assigned randomly to every player
  207. //TODO: allow customize teams in rmg template
  208. for(const auto & pair : mapGenOptions.getPlayersSettings())
  209. {
  210. const auto & pSettings = pair.second;
  211. PlayerInfo player;
  212. player.canComputerPlay = true;
  213. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  214. if (j == CPHUMAN)
  215. {
  216. player.canHumanPlay = true;
  217. }
  218. if (teamNumbers[j].empty())
  219. {
  220. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  221. assert (teamNumbers[j].size());
  222. }
  223. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  224. player.team = TeamID(*itTeam);
  225. teamNumbers[j].erase(itTeam);
  226. map->map().players[pSettings.getColor().getNum()] = player;
  227. }
  228. map->map().howManyTeams = (mapGenOptions.getTeamCount() == 0 ? mapGenOptions.getPlayerCount() : mapGenOptions.getTeamCount())
  229. + (mapGenOptions.getCompOnlyTeamCount() == 0 ? mapGenOptions.getCompOnlyPlayerCount() : mapGenOptions.getCompOnlyTeamCount());
  230. }
  231. void CMapGenerator::genZones()
  232. {
  233. CZonePlacer placer(*map);
  234. placer.placeZones(&rand);
  235. placer.assignZones(&rand);
  236. logGlobal->info("Zones generated successfully");
  237. }
  238. void CMapGenerator::createWaterTreasures()
  239. {
  240. if(!getZoneWater())
  241. return;
  242. //add treasures on water
  243. for(auto & treasureInfo : getConfig().waterTreasure)
  244. {
  245. getZoneWater()->addTreasureInfo(treasureInfo);
  246. }
  247. }
  248. void CMapGenerator::fillZones()
  249. {
  250. findZonesForQuestArts();
  251. createWaterTreasures();
  252. logGlobal->info("Started filling zones");
  253. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  254. //place main town in the middle
  255. for(auto it : map->getZones())
  256. {
  257. it.second->initFreeTiles();
  258. it.second->initModificators();
  259. }
  260. std::vector<std::shared_ptr<Zone>> treasureZones;
  261. for(auto it : map->getZones())
  262. {
  263. it.second->processModificators();
  264. if (it.second->getType() == ETemplateZoneType::TREASURE)
  265. treasureZones.push_back(it.second);
  266. }
  267. //find place for Grail
  268. if(treasureZones.empty())
  269. {
  270. for(auto it : map->getZones())
  271. if(it.second->getType() != ETemplateZoneType::WATER)
  272. treasureZones.push_back(it.second);
  273. }
  274. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  275. map->map().grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths().getTiles(), rand);
  276. logGlobal->info("Zones filled successfully");
  277. }
  278. void CMapGenerator::findZonesForQuestArts()
  279. {
  280. //we want to place arties in zones that were not yet filled (higher index)
  281. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  282. {
  283. auto zoneA = map->getZones()[connection.getZoneA()];
  284. auto zoneB = map->getZones()[connection.getZoneB()];
  285. if (zoneA->getId() > zoneB->getId())
  286. {
  287. if(auto * m = zoneB->getModificator<TreasurePlacer>())
  288. zoneB->getModificator<TreasurePlacer>()->setQuestArtZone(zoneA.get());
  289. }
  290. else if (zoneA->getId() < zoneB->getId())
  291. {
  292. if(auto * m = zoneA->getModificator<TreasurePlacer>())
  293. zoneA->getModificator<TreasurePlacer>()->setQuestArtZone(zoneB.get());
  294. }
  295. }
  296. }
  297. void CMapGenerator::addHeaderInfo()
  298. {
  299. map->map().version = EMapFormat::VCMI;
  300. map->map().width = mapGenOptions.getWidth();
  301. map->map().height = mapGenOptions.getHeight();
  302. map->map().twoLevel = mapGenOptions.getHasTwoLevels();
  303. map->map().name = VLC->generaltexth->allTexts[740];
  304. map->map().description = getMapDescription();
  305. map->map().difficulty = 1;
  306. addPlayerInfo();
  307. }
  308. int CMapGenerator::getNextMonlithIndex()
  309. {
  310. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  311. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  312. else
  313. return monolithIndex++;
  314. }
  315. int CMapGenerator::getPrisonsRemaning() const
  316. {
  317. return prisonsRemaining;
  318. }
  319. void CMapGenerator::decreasePrisonsRemaining()
  320. {
  321. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  322. }
  323. const std::vector<ArtifactID> & CMapGenerator::getQuestArtsRemaning() const
  324. {
  325. return questArtifacts;
  326. }
  327. void CMapGenerator::banQuestArt(ArtifactID id)
  328. {
  329. map->map().allowedArtifact[id] = false;
  330. vstd::erase_if_present(questArtifacts, id);
  331. }
  332. Zone * CMapGenerator::getZoneWater() const
  333. {
  334. for(auto & z : map->getZones())
  335. if(z.second->getType() == ETemplateZoneType::WATER)
  336. return z.second.get();
  337. return nullptr;
  338. }