CMapGenerator.cpp 16 KB

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