CMapGenerator.cpp 14 KB

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