CMapGenerator.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 "../GameLibrary.h"
  15. #include "../texts/CGeneralTextHandler.h"
  16. #include "../CRandomGenerator.h"
  17. #include "../entities/artifact/CArtHandler.h"
  18. #include "../entities/faction/CTownHandler.h"
  19. #include "../entities/faction/CFaction.h"
  20. #include "../entities/hero/CHero.h"
  21. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  22. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  23. #include "../mapping/CMapEditManager.h"
  24. #include "../constants/StringConstants.h"
  25. #include "../filesystem/Filesystem.h"
  26. #include "CZonePlacer.h"
  27. #include "CRoadRandomizer.h"
  28. #include "TileInfo.h"
  29. #include "Zone.h"
  30. #include "Functions.h"
  31. #include "RmgMap.h"
  32. #include "modificators/ObjectManager.h"
  33. #include "modificators/TreasurePlacer.h"
  34. #include "modificators/RoadPlacer.h"
  35. #include <vstd/RNG.h>
  36. #include <vcmi/HeroTypeService.h>
  37. #include <tbb/task_group.h>
  38. VCMI_LIB_NAMESPACE_BEGIN
  39. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, IGameInfoCallback * cb, int RandomSeed) :
  40. mapGenOptions(mapGenOptions), randomSeed(RandomSeed),
  41. monolithIndex(0),
  42. rand(std::make_unique<CRandomGenerator>(RandomSeed))
  43. {
  44. loadConfig();
  45. mapGenOptions.finalize(*rand);
  46. map = std::make_unique<RmgMap>(mapGenOptions, cb);
  47. placer = std::make_shared<CZonePlacer>(*map);
  48. }
  49. int CMapGenerator::getRandomSeed() const
  50. {
  51. return randomSeed;
  52. }
  53. void CMapGenerator::loadConfig()
  54. {
  55. JsonNode randomMapJson(JsonPath::builtin("config/randomMap.json"));
  56. config.shipyardGuard = randomMapJson["waterZone"]["shipyard"]["value"].Integer();
  57. for(auto & treasure : randomMapJson["waterZone"]["treasure"].Vector())
  58. {
  59. config.waterTreasure.emplace_back(treasure["min"].Integer(), treasure["max"].Integer(), treasure["density"].Integer());
  60. }
  61. config.mineExtraResources = randomMapJson["mines"]["extraResourcesLimit"].Integer();
  62. config.minGuardStrength = randomMapJson["minGuardStrength"].Integer();
  63. config.defaultRoadType = randomMapJson["defaultRoadType"].String();
  64. config.secondaryRoadType = randomMapJson["secondaryRoadType"].String();
  65. config.treasureValueLimit = randomMapJson["treasureValueLimit"].Integer();
  66. for(auto & i : randomMapJson["prisons"]["experience"].Vector())
  67. config.prisonExperience.push_back(i.Integer());
  68. for(auto & i : randomMapJson["prisons"]["value"].Vector())
  69. config.prisonValues.push_back(i.Integer());
  70. for(auto & i : randomMapJson["scrolls"]["value"].Vector())
  71. config.scrollValues.push_back(i.Integer());
  72. for(auto & i : randomMapJson["pandoras"]["creaturesValue"].Vector())
  73. config.pandoraCreatureValues.push_back(i.Integer());
  74. for(auto & i : randomMapJson["quests"]["value"].Vector())
  75. config.questValues.push_back(i.Integer());
  76. for(auto & i : randomMapJson["quests"]["rewardValue"].Vector())
  77. config.questRewardValues.push_back(i.Integer());
  78. config.seerHutValue = randomMapJson["quests"]["seerHutValue"].Integer();
  79. logGlobal->info("Seer Hut value: %d", config.seerHutValue);
  80. config.pandoraMultiplierGold = randomMapJson["pandoras"]["valueMultiplierGold"].Integer();
  81. config.pandoraMultiplierExperience = randomMapJson["pandoras"]["valueMultiplierExperience"].Integer();
  82. config.pandoraMultiplierSpells = randomMapJson["pandoras"]["valueMultiplierSpells"].Integer();
  83. config.pandoraSpellSchool = randomMapJson["pandoras"]["valueSpellSchool"].Integer();
  84. config.pandoraSpell60 = randomMapJson["pandoras"]["valueSpell60"].Integer();
  85. config.singleThread = randomMapJson["singleThread"].Bool();
  86. }
  87. const CMapGenerator::Config & CMapGenerator::getConfig() const
  88. {
  89. return config;
  90. }
  91. //must be instantiated in .cpp file for access to complete types of all member fields
  92. CMapGenerator::~CMapGenerator() = default;
  93. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  94. {
  95. return mapGenOptions;
  96. }
  97. void CMapGenerator::initQuestArtsRemaining()
  98. {
  99. //TODO: Move to QuestArtifactPlacer?
  100. for (auto artID : LIBRARY->arth->getDefaultAllowed())
  101. {
  102. auto art = artID.toArtifact();
  103. //Don't use parts of combined artifacts
  104. if (art->aClass == EArtifactClass::ART_TREASURE && LIBRARY->arth->legalArtifact(art->getId()) && art->getPartOf().empty())
  105. questArtifacts.push_back(art->getId());
  106. }
  107. }
  108. std::unique_ptr<CMap> CMapGenerator::generate()
  109. {
  110. Load::Progress::reset();
  111. Load::Progress::setupStepsTill(5, 30);
  112. try
  113. {
  114. addHeaderInfo();
  115. map->initTiles(*this, *rand);
  116. Load::Progress::step();
  117. initQuestArtsRemaining();
  118. genZones();
  119. Load::Progress::step();
  120. map->getMap(this).calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  121. map->addModificators();
  122. Load::Progress::step(3);
  123. fillZones();
  124. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  125. map->getZones().clear();
  126. // undo manager keeps pointers to object that might be removed during gameplay. Remove them to prevent any hanging pointer after gameplay
  127. map->getEditManager()->getUndoManager().clearAll();
  128. }
  129. catch (rmgException &e)
  130. {
  131. logGlobal->error("Random map generation received exception: %s", e.what());
  132. throw;
  133. }
  134. Load::Progress::finish();
  135. map->mapInstance->creationDateTime = std::time(nullptr);
  136. map->mapInstance->author = MetaString::createFromTextID("core.genrltxt.740");
  137. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  138. if(mapTemplate)
  139. map->mapInstance->mapVersion = MetaString::createFromRawString(mapTemplate->getName());
  140. return std::move(map->mapInstance);
  141. }
  142. MetaString CMapGenerator::getMapDescription() const
  143. {
  144. const TextIdentifier mainPattern("vcmi", "randomMap", "description");
  145. const TextIdentifier isHuman("vcmi", "randomMap", "description", "isHuman");
  146. const TextIdentifier townChoiceIs("vcmi", "randomMap", "description", "townChoice");
  147. const std::array waterContent = {
  148. TextIdentifier("vcmi", "randomMap", "description", "water", "none"),
  149. TextIdentifier("vcmi", "randomMap", "description", "water", "normal"),
  150. TextIdentifier("vcmi", "randomMap", "description", "water", "islands")
  151. };
  152. const std::array monsterStrength = {
  153. TextIdentifier("vcmi", "randomMap", "description", "monster", "weak"),
  154. TextIdentifier("vcmi", "randomMap", "description", "monster", "normal"),
  155. TextIdentifier("vcmi", "randomMap", "description", "monster", "strong")
  156. };
  157. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  158. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  159. MetaString result = MetaString::createFromTextID(mainPattern.get());
  160. result.replaceRawString(mapTemplate->getName());
  161. result.replaceNumber(map->width());
  162. result.replaceNumber(map->height());
  163. result.replaceNumber(map->levels());
  164. result.replaceNumber(mapGenOptions.getHumanOrCpuPlayerCount());
  165. result.replaceNumber(mapGenOptions.getCompOnlyPlayerCount());
  166. result.replaceTextID(waterContent.at(mapGenOptions.getWaterContent()).get());
  167. result.replaceTextID(monsterStrength.at(monsterStrengthIndex).get());
  168. for(const auto & pair : mapGenOptions.getPlayersSettings())
  169. {
  170. const auto & pSettings = pair.second;
  171. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  172. {
  173. result.appendTextID(isHuman.get());
  174. result.replaceName(pSettings.getColor());
  175. }
  176. if(pSettings.getStartingTown() != FactionID::RANDOM)
  177. {
  178. result.appendTextID(townChoiceIs.get());
  179. result.replaceName(pSettings.getColor());
  180. result.replaceName(pSettings.getStartingTown());
  181. }
  182. }
  183. return result;
  184. }
  185. void CMapGenerator::addPlayerInfo()
  186. {
  187. // Teams are already configured in CMapGenOptions. However, it's not the case when it comes to map editor
  188. std::set<TeamID> teamsTotal;
  189. if (mapGenOptions.arePlayersCustomized())
  190. {
  191. // Simply copy existing settings set in GUI
  192. for (const auto & player : mapGenOptions.getPlayersSettings())
  193. {
  194. PlayerInfo playerInfo;
  195. playerInfo.team = player.second.getTeam();
  196. if (player.second.getPlayerType() == EPlayerType::COMP_ONLY)
  197. {
  198. playerInfo.canHumanPlay = false;
  199. }
  200. else
  201. {
  202. playerInfo.canHumanPlay = true;
  203. }
  204. map->getMap(this).players[player.first.getNum()] = playerInfo;
  205. teamsTotal.insert(player.second.getTeam());
  206. }
  207. }
  208. else
  209. {
  210. // Assign standard teams (in map editor)
  211. // Calculate which team numbers exist
  212. 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
  213. std::array<std::list<int>, 2> teamNumbers;
  214. int teamOffset = 0;
  215. int playerCount = 0;
  216. int teamCount = 0;
  217. // FIXME: Player can be any color, not just 0
  218. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  219. {
  220. if (i == CPHUMAN)
  221. {
  222. playerCount = mapGenOptions.getHumanOrCpuPlayerCount();
  223. teamCount = mapGenOptions.getTeamCount();
  224. }
  225. else
  226. {
  227. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  228. teamCount = mapGenOptions.getCompOnlyTeamCount();
  229. }
  230. if(playerCount == 0)
  231. {
  232. continue;
  233. }
  234. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  235. int teamCountNorm = teamCount;
  236. if(teamCountNorm == 0)
  237. {
  238. teamCountNorm = playerCount;
  239. }
  240. for(int j = 0; j < teamCountNorm; ++j)
  241. {
  242. for(int k = 0; k < playersPerTeam; ++k)
  243. {
  244. teamNumbers[i].push_back(j + teamOffset);
  245. }
  246. }
  247. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  248. {
  249. teamNumbers[i].push_back(j + teamOffset);
  250. }
  251. teamOffset += teamCountNorm;
  252. }
  253. logGlobal->info("Current player settings size: %d", mapGenOptions.getPlayersSettings().size());
  254. // Team numbers are assigned randomly to every player
  255. //TODO: allow to customize teams in rmg template
  256. for(const auto & pair : mapGenOptions.getPlayersSettings())
  257. {
  258. const auto & pSettings = pair.second;
  259. PlayerInfo player;
  260. player.canComputerPlay = true;
  261. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  262. if (j == CPHUMAN)
  263. {
  264. player.canHumanPlay = true;
  265. }
  266. if(pSettings.getTeam() != TeamID::NO_TEAM)
  267. {
  268. player.team = pSettings.getTeam();
  269. }
  270. else
  271. {
  272. if (teamNumbers[j].empty())
  273. {
  274. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  275. assert (teamNumbers[j].size());
  276. }
  277. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], *rand);
  278. player.team = TeamID(*itTeam);
  279. teamNumbers[j].erase(itTeam);
  280. }
  281. teamsTotal.insert(player.team);
  282. map->getMap(this).players[pSettings.getColor().getNum()] = player;
  283. }
  284. logGlobal->info("Current team count: %d", teamsTotal.size());
  285. }
  286. // FIXME: 0
  287. // Can't find info for player 0 (starting zone)
  288. // Can't find info for player 1 (starting zone)
  289. map->getMap(this).howManyTeams = teamsTotal.size();
  290. }
  291. void CMapGenerator::genZones()
  292. {
  293. placer->placeZones(rand.get());
  294. placer->assignZones(rand.get());
  295. placer->RemoveRoadsForWideConnections();
  296. CRoadRandomizer roadRandomizer(*map);
  297. roadRandomizer.dropRandomRoads(rand.get());
  298. logGlobal->info("Zones generated successfully");
  299. }
  300. void CMapGenerator::addWaterTreasuresInfo()
  301. {
  302. if (!getZoneWater())
  303. return;
  304. //add treasures on water
  305. for (const auto& treasureInfo : getConfig().waterTreasure)
  306. {
  307. getZoneWater()->addTreasureInfo(treasureInfo);
  308. }
  309. }
  310. void CMapGenerator::fillZones()
  311. {
  312. addWaterTreasuresInfo();
  313. logGlobal->info("Started filling zones");
  314. size_t numZones = map->getZones().size();
  315. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  316. //place main town in the middle
  317. Load::Progress::setupStepsTill(numZones, 50);
  318. for (const auto& it : map->getZones())
  319. {
  320. it.second->initFreeTiles();
  321. it.second->initModificators();
  322. Progress::Progress::step();
  323. }
  324. std::vector<std::shared_ptr<Zone>> treasureZones;
  325. TModificators allJobs;
  326. for (auto& it : map->getZones())
  327. {
  328. allJobs.splice(allJobs.end(), it.second->getModificators());
  329. }
  330. Load::Progress::setupStepsTill(allJobs.size(), 240);
  331. if (config.singleThread) //No thread pool, just queue with deterministic order
  332. {
  333. while (!allJobs.empty())
  334. {
  335. for (auto it = allJobs.begin(); it != allJobs.end();)
  336. {
  337. if ((*it)->isReady())
  338. {
  339. auto jobCopy = *it;
  340. jobCopy->run();
  341. Progress::Progress::step(); //Update progress bar
  342. allJobs.erase(it);
  343. break; //Restart from the first job
  344. }
  345. else
  346. {
  347. ++it;
  348. }
  349. }
  350. }
  351. }
  352. else
  353. {
  354. tbb::task_group pool;
  355. while (!allJobs.empty())
  356. {
  357. for (auto it = allJobs.begin(); it != allJobs.end();)
  358. {
  359. if ((*it)->isFinished())
  360. {
  361. it = allJobs.erase(it);
  362. Progress::Progress::step();
  363. }
  364. else if ((*it)->isReady())
  365. {
  366. auto jobCopy = *it;
  367. pool.run([this, jobCopy]() -> void
  368. {
  369. jobCopy->run();
  370. Progress::Progress::step(); //Update progress bar
  371. }
  372. );
  373. it = allJobs.erase(it);
  374. }
  375. else
  376. {
  377. ++it;
  378. }
  379. }
  380. }
  381. //Wait for all the tasks
  382. pool.wait();
  383. }
  384. for (const auto& it : map->getZones())
  385. {
  386. if (it.second->getType() == ETemplateZoneType::TREASURE)
  387. treasureZones.push_back(it.second);
  388. }
  389. //find place for Grail
  390. if (treasureZones.empty())
  391. {
  392. for (const auto& it : map->getZones())
  393. if (it.second->getType() != ETemplateZoneType::WATER)
  394. treasureZones.push_back(it.second);
  395. }
  396. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, *rand);
  397. map->getMap(this).grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths()->getTiles(), *rand);
  398. map->getMap(this).reindexObjects();
  399. logGlobal->info("Zones filled successfully");
  400. Load::Progress::set(250);
  401. }
  402. void CMapGenerator::addHeaderInfo()
  403. {
  404. auto& m = map->getMap(this);
  405. m.version = EMapFormat::VCMI;
  406. m.width = mapGenOptions.getWidth();
  407. m.height = mapGenOptions.getHeight();
  408. m.mapLayers.clear();
  409. for(int i = 0; i < mapGenOptions.getLevels(); i++)
  410. {
  411. if(i == 0)
  412. m.mapLayers.push_back(MapLayerId::SURFACE);
  413. else if(i == 1)
  414. m.mapLayers.push_back(MapLayerId::UNDERGROUND);
  415. else
  416. m.mapLayers.push_back(MapLayerId::UNKNOWN); //TODO: multilevel support
  417. }
  418. m.name.appendLocalString(EMetaText::GENERAL_TXT, 740);
  419. m.description = getMapDescription();
  420. m.difficulty = EMapDifficulty::NORMAL;
  421. addPlayerInfo();
  422. m.waterMap = (mapGenOptions.getWaterContent() != EWaterContent::EWaterContent::NONE);
  423. m.banWaterContent();
  424. m.overrideGameSettings(mapGenOptions.getMapTemplate()->getMapSettings());
  425. for (const auto & spell : mapGenOptions.getMapTemplate()->getBannedSpells())
  426. m.allowedSpells.erase(spell);
  427. for (const auto & artifact : mapGenOptions.getMapTemplate()->getBannedArtifacts())
  428. m.allowedArtifact.erase(artifact);
  429. for (const auto & skill : mapGenOptions.getMapTemplate()->getBannedSkills())
  430. m.allowedAbilities.erase(skill);
  431. for (const auto & hero : mapGenOptions.getMapTemplate()->getBannedHeroes())
  432. m.allowedHeroes.erase(hero);
  433. for (const auto & spell : mapGenOptions.getMapTemplate()->getEnabledSpells())
  434. m.allowedSpells.insert(spell);
  435. for (const auto & artifact : mapGenOptions.getMapTemplate()->getEnabledArtifacts())
  436. m.allowedArtifact.insert(artifact);
  437. for (const auto & skill : mapGenOptions.getMapTemplate()->getEnabledSkills())
  438. m.allowedAbilities.insert(skill);
  439. for (const auto & hero : mapGenOptions.getMapTemplate()->getEnabledHeroes())
  440. m.allowedHeroes.insert(hero);
  441. }
  442. int CMapGenerator::getNextMonlithIndex()
  443. {
  444. while (true)
  445. {
  446. if (monolithIndex >= LIBRARY->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  447. throw rmgException(boost::str(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  448. else
  449. {
  450. //Skip modded Monoliths which can't beplaced on every terrain
  451. auto templates = LIBRARY->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, monolithIndex)->getTemplates();
  452. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  453. {
  454. monolithIndex++;
  455. }
  456. else
  457. {
  458. return monolithIndex++;
  459. }
  460. }
  461. }
  462. }
  463. std::shared_ptr<CZonePlacer> CMapGenerator::getZonePlacer() const
  464. {
  465. return placer;
  466. }
  467. const std::vector<ArtifactID> & CMapGenerator::getAllPossibleQuestArtifacts() const
  468. {
  469. return questArtifacts;
  470. }
  471. const std::vector<HeroTypeID> CMapGenerator::getAllPossibleHeroes() const
  472. {
  473. auto isWaterMap = map->getMap(this).isWaterMap();
  474. //Skip heroes that were banned, including the ones placed in prisons
  475. std::vector<HeroTypeID> ret;
  476. for (HeroTypeID hero : map->getMap(this).allowedHeroes)
  477. {
  478. auto * h = dynamic_cast<const CHero*>(LIBRARY->heroTypes()->getById(hero));
  479. if(h->onlyOnWaterMap && !isWaterMap)
  480. continue;
  481. if(h->onlyOnMapWithoutWater && isWaterMap)
  482. continue;
  483. bool heroUsedAsStarting = false;
  484. for (auto const & player : map->getMapGenOptions().getPlayersSettings())
  485. {
  486. if (player.second.getStartingHero() == hero)
  487. {
  488. heroUsedAsStarting = true;
  489. break;
  490. }
  491. }
  492. if (heroUsedAsStarting)
  493. continue;
  494. ret.push_back(hero);
  495. }
  496. return ret;
  497. }
  498. void CMapGenerator::banQuestArt(const ArtifactID & id)
  499. {
  500. map->getMap(this).allowedArtifact.erase(id);
  501. }
  502. void CMapGenerator::unbanQuestArt(const ArtifactID & id)
  503. {
  504. map->getMap(this).allowedArtifact.insert(id);
  505. }
  506. Zone * CMapGenerator::getZoneWater() const
  507. {
  508. for(auto & z : map->getZones())
  509. if(z.second->getType() == ETemplateZoneType::WATER)
  510. return z.second.get();
  511. return nullptr;
  512. }
  513. VCMI_LIB_NAMESPACE_END