2
0

CMapGenerator.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 "threadpool/ThreadPool.h"
  26. #include "ObjectManager.h"
  27. #include "TreasurePlacer.h"
  28. #include "RoadPlacer.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, int RandomSeed) :
  31. mapGenOptions(mapGenOptions), randomSeed(RandomSeed),
  32. allowedPrisons(0), monolithIndex(0)
  33. {
  34. loadConfig();
  35. rand.setSeed(this->randomSeed);
  36. mapGenOptions.finalize(rand);
  37. map = std::make_unique<RmgMap>(mapGenOptions);
  38. placer = std::make_shared<CZonePlacer>(*map);
  39. }
  40. int CMapGenerator::getRandomSeed() const
  41. {
  42. return randomSeed;
  43. }
  44. void CMapGenerator::loadConfig()
  45. {
  46. static const ResourceID path("config/randomMap.json");
  47. JsonNode randomMapJson(path);
  48. config.shipyardGuard = randomMapJson["waterZone"]["shipyard"]["value"].Integer();
  49. for(auto & treasure : randomMapJson["waterZone"]["treasure"].Vector())
  50. {
  51. config.waterTreasure.emplace_back(treasure["min"].Integer(), treasure["max"].Integer(), treasure["density"].Integer());
  52. }
  53. config.mineExtraResources = randomMapJson["mines"]["extraResourcesLimit"].Integer();
  54. config.minGuardStrength = randomMapJson["minGuardStrength"].Integer();
  55. config.defaultRoadType = randomMapJson["defaultRoadType"].String();
  56. config.secondaryRoadType = randomMapJson["secondaryRoadType"].String();
  57. config.treasureValueLimit = randomMapJson["treasureValueLimit"].Integer();
  58. for(auto & i : randomMapJson["prisons"]["experience"].Vector())
  59. config.prisonExperience.push_back(i.Integer());
  60. for(auto & i : randomMapJson["prisons"]["value"].Vector())
  61. config.prisonValues.push_back(i.Integer());
  62. for(auto & i : randomMapJson["scrolls"]["value"].Vector())
  63. config.scrollValues.push_back(i.Integer());
  64. for(auto & i : randomMapJson["pandoras"]["creaturesValue"].Vector())
  65. config.pandoraCreatureValues.push_back(i.Integer());
  66. for(auto & i : randomMapJson["quests"]["value"].Vector())
  67. config.questValues.push_back(i.Integer());
  68. for(auto & i : randomMapJson["quests"]["rewardValue"].Vector())
  69. config.questRewardValues.push_back(i.Integer());
  70. config.pandoraMultiplierGold = randomMapJson["pandoras"]["valueMultiplierGold"].Integer();
  71. config.pandoraMultiplierExperience = randomMapJson["pandoras"]["valueMultiplierExperience"].Integer();
  72. config.pandoraMultiplierSpells = randomMapJson["pandoras"]["valueMultiplierSpells"].Integer();
  73. config.pandoraSpellSchool = randomMapJson["pandoras"]["valueSpellSchool"].Integer();
  74. config.pandoraSpell60 = randomMapJson["pandoras"]["valueSpell60"].Integer();
  75. //override config with game options
  76. if(!mapGenOptions.isRoadEnabled(config.secondaryRoadType))
  77. config.secondaryRoadType = "";
  78. if(!mapGenOptions.isRoadEnabled(config.defaultRoadType))
  79. config.defaultRoadType = config.secondaryRoadType;
  80. }
  81. const CMapGenerator::Config & CMapGenerator::getConfig() const
  82. {
  83. return config;
  84. }
  85. //must be instantiated in .cpp file for access to complete types of all member fields
  86. CMapGenerator::~CMapGenerator() = default;
  87. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  88. {
  89. return mapGenOptions;
  90. }
  91. void CMapGenerator::initPrisonsRemaining()
  92. {
  93. allowedPrisons = 0;
  94. for (auto isAllowed : map->map().allowedHeroes)
  95. {
  96. if (isAllowed)
  97. allowedPrisons++;
  98. }
  99. allowedPrisons = std::max<int> (0, allowedPrisons - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player
  100. }
  101. void CMapGenerator::initQuestArtsRemaining()
  102. {
  103. //TODO: Move to QuestArtifactPlacer?
  104. for (auto art : VLC->arth->objects)
  105. {
  106. //Don't use parts of combined artifacts
  107. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->getId()) && art->constituentOf.empty())
  108. questArtifacts.push_back(art->getId());
  109. }
  110. }
  111. std::unique_ptr<CMap> CMapGenerator::generate()
  112. {
  113. Load::Progress::reset();
  114. Load::Progress::setupStepsTill(5, 30);
  115. try
  116. {
  117. addHeaderInfo();
  118. map->initTiles(*this);
  119. Load::Progress::step();
  120. initPrisonsRemaining();
  121. initQuestArtsRemaining();
  122. genZones();
  123. Load::Progress::step();
  124. map->map().calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  125. map->addModificators();
  126. Load::Progress::step(3);
  127. fillZones();
  128. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  129. map->getZones().clear();
  130. }
  131. catch (rmgException &e)
  132. {
  133. logGlobal->error("Random map generation received exception: %s", e.what());
  134. }
  135. Load::Progress::finish();
  136. return std::move(map->mapInstance);
  137. }
  138. std::string CMapGenerator::getMapDescription() const
  139. {
  140. assert(map);
  141. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  142. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  143. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  144. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  145. if(!mapTemplate)
  146. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  147. std::stringstream ss;
  148. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  149. ", levels %d, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  150. randomSeed % map->map().width % map->map().height % static_cast<int>(map->map().levels()) % static_cast<int>(mapGenOptions.getPlayerCount()) %
  151. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  152. monsterStrengthStr[monsterStrengthIndex]);
  153. for(const auto & pair : mapGenOptions.getPlayersSettings())
  154. {
  155. const auto & pSettings = pair.second;
  156. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  157. {
  158. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  159. }
  160. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  161. {
  162. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  163. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->getNameTranslated();
  164. }
  165. }
  166. return ss.str();
  167. }
  168. void CMapGenerator::addPlayerInfo()
  169. {
  170. // Calculate which team numbers exist
  171. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  172. std::array<std::list<int>, 2> teamNumbers;
  173. std::set<int> teamsTotal;
  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(pSettings.getTeam() != TeamID::NO_TEAM)
  225. {
  226. player.team = pSettings.getTeam();
  227. }
  228. else
  229. {
  230. if (teamNumbers[j].empty())
  231. {
  232. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  233. assert (teamNumbers[j].size());
  234. }
  235. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  236. player.team = TeamID(*itTeam);
  237. teamNumbers[j].erase(itTeam);
  238. }
  239. teamsTotal.insert(player.team.getNum());
  240. map->map().players[pSettings.getColor().getNum()] = player;
  241. }
  242. map->map().howManyTeams = teamsTotal.size();
  243. }
  244. void CMapGenerator::genZones()
  245. {
  246. placer->placeZones(&rand);
  247. placer->assignZones(&rand);
  248. logGlobal->info("Zones generated successfully");
  249. }
  250. void CMapGenerator::addWaterTreasuresInfo()
  251. {
  252. if (!getZoneWater())
  253. return;
  254. //add treasures on water
  255. for (const auto& treasureInfo : getConfig().waterTreasure)
  256. {
  257. getZoneWater()->addTreasureInfo(treasureInfo);
  258. }
  259. }
  260. void CMapGenerator::fillZones()
  261. {
  262. addWaterTreasuresInfo();
  263. logGlobal->info("Started filling zones");
  264. size_t numZones = map->getZones().size();
  265. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  266. //place main town in the middle
  267. Load::Progress::setupStepsTill(numZones, 50);
  268. for (const auto& it : map->getZones())
  269. {
  270. it.second->initFreeTiles();
  271. it.second->initModificators();
  272. Progress::Progress::step();
  273. }
  274. //TODO: multiply by the number of modificators
  275. Load::Progress::setupStepsTill(numZones, 240);
  276. std::vector<std::shared_ptr<Zone>> treasureZones;
  277. ThreadPool pool;
  278. std::vector<boost::future<void>> futures;
  279. //At most one Modificator can run for every zone
  280. pool.init(std::min<int>(std::thread::hardware_concurrency(), numZones));
  281. while (hasJobs())
  282. {
  283. auto job = getNextJob();
  284. if (job)
  285. {
  286. futures.push_back(pool.async([this, job]() -> void
  287. {
  288. job.value()();
  289. Progress::Progress::step(); //Update progress bar
  290. }
  291. ));
  292. }
  293. }
  294. //Wait for all the tasks
  295. for (auto& fut : futures)
  296. {
  297. fut.get();
  298. }
  299. for (const auto& it : map->getZones())
  300. {
  301. if (it.second->getType() == ETemplateZoneType::TREASURE)
  302. treasureZones.push_back(it.second);
  303. }
  304. //find place for Grail
  305. if (treasureZones.empty())
  306. {
  307. for (const auto& it : map->getZones())
  308. if (it.second->getType() != ETemplateZoneType::WATER)
  309. treasureZones.push_back(it.second);
  310. }
  311. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  312. map->map().grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths().getTiles(), rand);
  313. logGlobal->info("Zones filled successfully");
  314. Load::Progress::set(250);
  315. }
  316. void CMapGenerator::addHeaderInfo()
  317. {
  318. map->map().version = EMapFormat::VCMI;
  319. map->map().width = mapGenOptions.getWidth();
  320. map->map().height = mapGenOptions.getHeight();
  321. map->map().twoLevel = mapGenOptions.getHasTwoLevels();
  322. map->map().name = VLC->generaltexth->allTexts[740];
  323. map->map().description = getMapDescription();
  324. map->map().difficulty = 1;
  325. addPlayerInfo();
  326. }
  327. int CMapGenerator::getNextMonlithIndex()
  328. {
  329. while (true)
  330. {
  331. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  332. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  333. else
  334. {
  335. //Skip modded Monoliths which can't beplaced on every terrain
  336. auto templates = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, monolithIndex)->getTemplates();
  337. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  338. {
  339. monolithIndex++;
  340. }
  341. else
  342. {
  343. return monolithIndex++;
  344. }
  345. }
  346. }
  347. }
  348. int CMapGenerator::getPrisonsRemaning() const
  349. {
  350. return allowedPrisons;
  351. }
  352. std::shared_ptr<CZonePlacer> CMapGenerator::getZonePlacer() const
  353. {
  354. return placer;
  355. }
  356. const std::vector<ArtifactID> & CMapGenerator::getAllPossibleQuestArtifacts() const
  357. {
  358. return questArtifacts;
  359. }
  360. const std::vector<HeroTypeID> CMapGenerator::getAllPossibleHeroes() const
  361. {
  362. //Skip heroes that were banned, including the ones placed in prisons
  363. std::vector<HeroTypeID> ret;
  364. for (int j = 0; j < map->map().allowedHeroes.size(); j++)
  365. {
  366. if (map->map().allowedHeroes[j])
  367. ret.push_back(HeroTypeID(j));
  368. }
  369. return ret;
  370. }
  371. void CMapGenerator::banQuestArt(const ArtifactID & id)
  372. {
  373. //TODO: Protect with mutex
  374. map->map().allowedArtifact[id] = false;
  375. }
  376. void CMapGenerator::banHero(const HeroTypeID & id)
  377. {
  378. //TODO: Protect with mutex
  379. map->map().allowedHeroes[id] = false;
  380. }
  381. Zone * CMapGenerator::getZoneWater() const
  382. {
  383. for(auto & z : map->getZones())
  384. if(z.second->getType() == ETemplateZoneType::WATER)
  385. return z.second.get();
  386. return nullptr;
  387. }
  388. bool CMapGenerator::hasJobs()
  389. {
  390. for (auto zone : map->getZones())
  391. {
  392. if (zone.second->hasJobs())
  393. {
  394. return true;
  395. }
  396. }
  397. return false;
  398. }
  399. TRMGJob CMapGenerator::getNextJob()
  400. {
  401. for (auto zone : map->getZones())
  402. {
  403. if (zone.second->hasJobs())
  404. {
  405. return zone.second->getNextJob();
  406. }
  407. }
  408. return TRMGJob();
  409. }
  410. VCMI_LIB_NAMESPACE_END