CMapGenerator.cpp 15 KB

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