CMapGenerator.cpp 12 KB

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