CMapGenerator.cpp 15 KB

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