CMapGenerator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. Load::Progress::reset();
  115. Load::Progress::setupStepsTill(5, 30);
  116. try
  117. {
  118. addHeaderInfo();
  119. map->initTiles(*this);
  120. Load::Progress::step();
  121. initPrisonsRemaining();
  122. initQuestArtsRemaining();
  123. genZones();
  124. Load::Progress::step();
  125. map->map().calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  126. map->addModificators();
  127. Load::Progress::step(3);
  128. fillZones();
  129. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  130. map->getZones().clear();
  131. }
  132. catch (rmgException &e)
  133. {
  134. logGlobal->error("Random map generation received exception: %s", e.what());
  135. }
  136. Load::Progress::finish();
  137. return std::move(map->mapInstance);
  138. }
  139. std::string CMapGenerator::getMapDescription() const
  140. {
  141. assert(map);
  142. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  143. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  144. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  145. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  146. if(!mapTemplate)
  147. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  148. std::stringstream ss;
  149. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  150. ", levels %d, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  151. randomSeed % map->map().width % map->map().height % map->map().levels() % static_cast<int>(mapGenOptions.getPlayerCount()) %
  152. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  153. monsterStrengthStr[monsterStrengthIndex]);
  154. for(const auto & pair : mapGenOptions.getPlayersSettings())
  155. {
  156. const auto & pSettings = pair.second;
  157. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  158. {
  159. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  160. }
  161. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  162. {
  163. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  164. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->name;
  165. }
  166. }
  167. return ss.str();
  168. }
  169. void CMapGenerator::addPlayerInfo()
  170. {
  171. // Calculate which team numbers exist
  172. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  173. std::array<std::list<int>, 2> teamNumbers;
  174. int teamOffset = 0;
  175. int playerCount = 0;
  176. int teamCount = 0;
  177. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  178. {
  179. if (i == CPHUMAN)
  180. {
  181. playerCount = mapGenOptions.getPlayerCount();
  182. teamCount = mapGenOptions.getTeamCount();
  183. }
  184. else
  185. {
  186. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  187. teamCount = mapGenOptions.getCompOnlyTeamCount();
  188. }
  189. if(playerCount == 0)
  190. {
  191. continue;
  192. }
  193. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  194. int teamCountNorm = teamCount;
  195. if(teamCountNorm == 0)
  196. {
  197. teamCountNorm = playerCount;
  198. }
  199. for(int j = 0; j < teamCountNorm; ++j)
  200. {
  201. for(int k = 0; k < playersPerTeam; ++k)
  202. {
  203. teamNumbers[i].push_back(j + teamOffset);
  204. }
  205. }
  206. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  207. {
  208. teamNumbers[i].push_back(j + teamOffset);
  209. }
  210. teamOffset += teamCountNorm;
  211. }
  212. // Team numbers are assigned randomly to every player
  213. //TODO: allow customize teams in rmg template
  214. for(const auto & pair : mapGenOptions.getPlayersSettings())
  215. {
  216. const auto & pSettings = pair.second;
  217. PlayerInfo player;
  218. player.canComputerPlay = true;
  219. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  220. if (j == CPHUMAN)
  221. {
  222. player.canHumanPlay = true;
  223. }
  224. if (teamNumbers[j].empty())
  225. {
  226. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  227. assert (teamNumbers[j].size());
  228. }
  229. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  230. player.team = TeamID(*itTeam);
  231. teamNumbers[j].erase(itTeam);
  232. map->map().players[pSettings.getColor().getNum()] = player;
  233. }
  234. map->map().howManyTeams = (mapGenOptions.getTeamCount() == 0 ? mapGenOptions.getPlayerCount() : mapGenOptions.getTeamCount())
  235. + (mapGenOptions.getCompOnlyTeamCount() == 0 ? mapGenOptions.getCompOnlyPlayerCount() : mapGenOptions.getCompOnlyTeamCount());
  236. }
  237. void CMapGenerator::genZones()
  238. {
  239. CZonePlacer placer(*map);
  240. placer.placeZones(&rand);
  241. placer.assignZones(&rand);
  242. logGlobal->info("Zones generated successfully");
  243. }
  244. void CMapGenerator::createWaterTreasures()
  245. {
  246. if(!getZoneWater())
  247. return;
  248. //add treasures on water
  249. for(auto & treasureInfo : getConfig().waterTreasure)
  250. {
  251. getZoneWater()->addTreasureInfo(treasureInfo);
  252. }
  253. }
  254. void CMapGenerator::fillZones()
  255. {
  256. findZonesForQuestArts();
  257. createWaterTreasures();
  258. logGlobal->info("Started filling zones");
  259. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  260. //place main town in the middle
  261. Load::Progress::setupStepsTill(map->getZones().size(), 50);
  262. for(auto it : map->getZones())
  263. {
  264. it.second->initFreeTiles();
  265. it.second->initModificators();
  266. Progress::Progress::step();
  267. }
  268. Load::Progress::setupStepsTill(map->getZones().size(), 240);
  269. std::vector<std::shared_ptr<Zone>> treasureZones;
  270. for(auto it : map->getZones())
  271. {
  272. it.second->processModificators();
  273. if (it.second->getType() == ETemplateZoneType::TREASURE)
  274. treasureZones.push_back(it.second);
  275. Progress::Progress::step();
  276. }
  277. //find place for Grail
  278. if(treasureZones.empty())
  279. {
  280. for(auto it : map->getZones())
  281. if(it.second->getType() != ETemplateZoneType::WATER)
  282. treasureZones.push_back(it.second);
  283. }
  284. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  285. map->map().grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths().getTiles(), rand);
  286. logGlobal->info("Zones filled successfully");
  287. Load::Progress::set(250);
  288. }
  289. void CMapGenerator::findZonesForQuestArts()
  290. {
  291. //we want to place arties in zones that were not yet filled (higher index)
  292. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  293. {
  294. auto zoneA = map->getZones()[connection.getZoneA()];
  295. auto zoneB = map->getZones()[connection.getZoneB()];
  296. if (zoneA->getId() > zoneB->getId())
  297. {
  298. if(auto * m = zoneB->getModificator<TreasurePlacer>())
  299. zoneB->getModificator<TreasurePlacer>()->setQuestArtZone(zoneA.get());
  300. }
  301. else if (zoneA->getId() < zoneB->getId())
  302. {
  303. if(auto * m = zoneA->getModificator<TreasurePlacer>())
  304. zoneA->getModificator<TreasurePlacer>()->setQuestArtZone(zoneB.get());
  305. }
  306. }
  307. }
  308. void CMapGenerator::addHeaderInfo()
  309. {
  310. map->map().version = EMapFormat::VCMI;
  311. map->map().width = mapGenOptions.getWidth();
  312. map->map().height = mapGenOptions.getHeight();
  313. map->map().twoLevel = mapGenOptions.getHasTwoLevels();
  314. map->map().name = VLC->generaltexth->allTexts[740];
  315. map->map().description = getMapDescription();
  316. map->map().difficulty = 1;
  317. addPlayerInfo();
  318. }
  319. int CMapGenerator::getNextMonlithIndex()
  320. {
  321. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  322. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  323. else
  324. return monolithIndex++;
  325. }
  326. int CMapGenerator::getPrisonsRemaning() const
  327. {
  328. return prisonsRemaining;
  329. }
  330. void CMapGenerator::decreasePrisonsRemaining()
  331. {
  332. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  333. }
  334. const std::vector<ArtifactID> & CMapGenerator::getQuestArtsRemaning() const
  335. {
  336. return questArtifacts;
  337. }
  338. void CMapGenerator::banQuestArt(ArtifactID id)
  339. {
  340. map->map().allowedArtifact[id] = false;
  341. vstd::erase_if_present(questArtifacts, id);
  342. }
  343. Zone * CMapGenerator::getZoneWater() const
  344. {
  345. for(auto & z : map->getZones())
  346. if(z.second->getType() == ETemplateZoneType::WATER)
  347. return z.second.get();
  348. return nullptr;
  349. }