CMapGenerator.cpp 14 KB

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