CMapGenerator.cpp 15 KB

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