CMapGenerator.cpp 12 KB

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