CMapGenerator.cpp 15 KB

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