CMapGenerator.cpp 14 KB

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