CMapGenerator.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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 "../VCMI_Lib.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../mapping/CMapEditManager.h"
  16. #include "../CTownHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "CZonePlacer.h"
  20. #include "CRmgTemplateZone.h"
  21. #include "../mapObjects/CObjectClassesHandler.h"
  22. static const int3 dirs4[] = {int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0)};
  23. static const int3 dirsDiagonal[] = { int3(1,1,0),int3(1,-1,0),int3(-1,1,0),int3(-1,-1,0) };
  24. void CMapGenerator::foreach_neighbour(const int3 &pos, std::function<void(int3& pos)> foo)
  25. {
  26. for(const int3 &dir : int3::getDirs())
  27. {
  28. int3 n = pos + dir;
  29. /*important notice: perform any translation before this function is called,
  30. so the actual map position is checked*/
  31. if(map->isInTheMap(n))
  32. foo(n);
  33. }
  34. }
  35. void CMapGenerator::foreachDirectNeighbour(const int3& pos, std::function<void(int3& pos)> foo)
  36. {
  37. for(const int3 &dir : dirs4)
  38. {
  39. int3 n = pos + dir;
  40. if(map->isInTheMap(n))
  41. foo(n);
  42. }
  43. }
  44. void CMapGenerator::foreachDiagonalNeighbour(const int3& pos, std::function<void(int3& pos)> foo)
  45. {
  46. for (const int3 &dir : dirsDiagonal)
  47. {
  48. int3 n = pos + dir;
  49. if (map->isInTheMap(n))
  50. foo(n);
  51. }
  52. }
  53. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, int RandomSeed) :
  54. mapGenOptions(mapGenOptions), randomSeed(RandomSeed),
  55. zonesTotal(0), tiles(nullptr), prisonsRemaining(0),
  56. monolithIndex(0)
  57. {
  58. loadConfig();
  59. rand.setSeed(this->randomSeed);
  60. mapGenOptions.finalize(rand);
  61. }
  62. void CMapGenerator::loadConfig()
  63. {
  64. static const std::map<std::string, Res::ERes> resMap
  65. {
  66. {"wood", Res::ERes::WOOD},
  67. {"ore", Res::ERes::ORE},
  68. {"gems", Res::ERes::GEMS},
  69. {"crystal", Res::ERes::CRYSTAL},
  70. {"mercury", Res::ERes::MERCURY},
  71. {"sulfur", Res::ERes::SULFUR},
  72. {"gold", Res::ERes::GOLD},
  73. };
  74. static const ResourceID path("config/randomMap.json");
  75. JsonNode randomMapJson(path);
  76. for(auto& s : randomMapJson["terrain"]["undergroundAllow"].Vector())
  77. {
  78. if(!s.isNull())
  79. config.terrainUndergroundAllowed.emplace_back(s.String());
  80. }
  81. for(auto& s : randomMapJson["terrain"]["groundProhibit"].Vector())
  82. {
  83. if(!s.isNull())
  84. config.terrainGroundProhibit.emplace_back(s.String());
  85. }
  86. config.shipyardGuard = randomMapJson["waterZone"]["shipyard"]["value"].Integer();
  87. for(auto & treasure : randomMapJson["waterZone"]["treasure"].Vector())
  88. {
  89. config.waterTreasure.emplace_back(treasure["min"].Integer(), treasure["max"].Integer(), treasure["density"].Integer());
  90. }
  91. for(auto& s : resMap)
  92. {
  93. config.mineValues[s.second] = randomMapJson["mines"]["value"][s.first].Integer();
  94. }
  95. config.mineExtraResources = randomMapJson["mines"]["extraResourcesLimit"].Integer();
  96. config.minGuardStrength = randomMapJson["minGuardStrength"].Integer();
  97. config.defaultRoadType = randomMapJson["defaultRoadType"].String();
  98. config.treasureValueLimit = randomMapJson["treasureValueLimit"].Integer();
  99. for(auto & i : randomMapJson["prisons"]["experience"].Vector())
  100. config.prisonExperience.push_back(i.Integer());
  101. for(auto & i : randomMapJson["prisons"]["value"].Vector())
  102. config.prisonValues.push_back(i.Integer());
  103. for(auto & i : randomMapJson["scrolls"]["value"].Vector())
  104. config.scrollValues.push_back(i.Integer());
  105. for(auto & i : randomMapJson["pandoras"]["creaturesValue"].Vector())
  106. config.pandoraCreatureValues.push_back(i.Integer());
  107. for(auto & i : randomMapJson["quests"]["value"].Vector())
  108. config.questValues.push_back(i.Integer());
  109. for(auto & i : randomMapJson["quests"]["rewardValue"].Vector())
  110. config.questRewardValues.push_back(i.Integer());
  111. config.pandoraMultiplierGold = randomMapJson["pandoras"]["valueMultiplierGold"].Integer();
  112. config.pandoraMultiplierExperience = randomMapJson["pandoras"]["valueMultiplierExperience"].Integer();
  113. config.pandoraMultiplierSpells = randomMapJson["pandoras"]["valueMultiplierSpells"].Integer();
  114. config.pandoraSpellSchool = randomMapJson["pandoras"]["valueSpellSchool"].Integer();
  115. config.pandoraSpell60 = randomMapJson["pandoras"]["valueSpell60"].Integer();
  116. }
  117. const CMapGenerator::Config & CMapGenerator::getConfig() const
  118. {
  119. return config;
  120. }
  121. void CMapGenerator::initTiles()
  122. {
  123. map->initTerrain();
  124. int width = map->width;
  125. int height = map->height;
  126. int level = map->twoLevel ? 2 : 1;
  127. tiles = new CTileInfo**[width];
  128. for (int i = 0; i < width; ++i)
  129. {
  130. tiles[i] = new CTileInfo*[height];
  131. for (int j = 0; j < height; ++j)
  132. {
  133. tiles[i][j] = new CTileInfo[level];
  134. }
  135. }
  136. zoneColouring.resize(boost::extents[map->twoLevel ? 2 : 1][map->width][map->height]);
  137. }
  138. CMapGenerator::~CMapGenerator()
  139. {
  140. if (tiles)
  141. {
  142. int width = mapGenOptions.getWidth();
  143. int height = mapGenOptions.getHeight();
  144. for (int i=0; i < width; i++)
  145. {
  146. for(int j=0; j < height; j++)
  147. {
  148. delete [] tiles[i][j];
  149. }
  150. delete [] tiles[i];
  151. }
  152. delete [] tiles;
  153. }
  154. }
  155. void CMapGenerator::initPrisonsRemaining()
  156. {
  157. prisonsRemaining = 0;
  158. for (auto isAllowed : map->allowedHeroes)
  159. {
  160. if (isAllowed)
  161. prisonsRemaining++;
  162. }
  163. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player
  164. }
  165. void CMapGenerator::initQuestArtsRemaining()
  166. {
  167. for (auto art : VLC->arth->objects)
  168. {
  169. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->id) && art->constituentOf.empty()) //don't use parts of combined artifacts
  170. questArtifacts.push_back(art->id);
  171. }
  172. }
  173. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  174. {
  175. return mapGenOptions;
  176. }
  177. CMapEditManager* CMapGenerator::getEditManager() const
  178. {
  179. if(!map)
  180. return nullptr;
  181. return map->getEditManager();
  182. }
  183. std::unique_ptr<CMap> CMapGenerator::generate()
  184. {
  185. map = make_unique<CMap>();
  186. try
  187. {
  188. map->getEditManager()->getUndoManager().setUndoRedoLimit(0);
  189. //FIXME: somehow mapGenOption is nullptr at this point :?
  190. addHeaderInfo();
  191. initTiles();
  192. initPrisonsRemaining();
  193. initQuestArtsRemaining();
  194. genZones();
  195. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  196. fillZones();
  197. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  198. zones.clear();
  199. }
  200. catch (rmgException &e)
  201. {
  202. logGlobal->error("Random map generation received exception: %s", e.what());
  203. }
  204. return std::move(map);
  205. }
  206. std::string CMapGenerator::getMapDescription() const
  207. {
  208. assert(map);
  209. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  210. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  211. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  212. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  213. if(!mapTemplate)
  214. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  215. std::stringstream ss;
  216. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  217. ", levels %s, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  218. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions.getPlayerCount()) %
  219. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  220. monsterStrengthStr[monsterStrengthIndex]);
  221. for(const auto & pair : mapGenOptions.getPlayersSettings())
  222. {
  223. const auto & pSettings = pair.second;
  224. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  225. {
  226. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  227. }
  228. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  229. {
  230. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  231. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->name;
  232. }
  233. }
  234. return ss.str();
  235. }
  236. void CMapGenerator::addPlayerInfo()
  237. {
  238. // Calculate which team numbers exist
  239. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  240. std::array<std::list<int>, 2> teamNumbers;
  241. int teamOffset = 0;
  242. int playerCount = 0;
  243. int teamCount = 0;
  244. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  245. {
  246. if (i == CPHUMAN)
  247. {
  248. playerCount = mapGenOptions.getPlayerCount();
  249. teamCount = mapGenOptions.getTeamCount();
  250. }
  251. else
  252. {
  253. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  254. teamCount = mapGenOptions.getCompOnlyTeamCount();
  255. }
  256. if(playerCount == 0)
  257. {
  258. continue;
  259. }
  260. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  261. int teamCountNorm = teamCount;
  262. if(teamCountNorm == 0)
  263. {
  264. teamCountNorm = playerCount;
  265. }
  266. for(int j = 0; j < teamCountNorm; ++j)
  267. {
  268. for(int k = 0; k < playersPerTeam; ++k)
  269. {
  270. teamNumbers[i].push_back(j + teamOffset);
  271. }
  272. }
  273. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  274. {
  275. teamNumbers[i].push_back(j + teamOffset);
  276. }
  277. teamOffset += teamCountNorm;
  278. }
  279. // Team numbers are assigned randomly to every player
  280. //TODO: allow customize teams in rmg template
  281. for(const auto & pair : mapGenOptions.getPlayersSettings())
  282. {
  283. const auto & pSettings = pair.second;
  284. PlayerInfo player;
  285. player.canComputerPlay = true;
  286. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  287. if (j == CPHUMAN)
  288. {
  289. player.canHumanPlay = true;
  290. }
  291. if (teamNumbers[j].empty())
  292. {
  293. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  294. assert (teamNumbers[j].size());
  295. }
  296. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  297. player.team = TeamID(*itTeam);
  298. teamNumbers[j].erase(itTeam);
  299. map->players[pSettings.getColor().getNum()] = player;
  300. }
  301. map->howManyTeams = (mapGenOptions.getTeamCount() == 0 ? mapGenOptions.getPlayerCount() : mapGenOptions.getTeamCount())
  302. + (mapGenOptions.getCompOnlyTeamCount() == 0 ? mapGenOptions.getCompOnlyPlayerCount() : mapGenOptions.getCompOnlyTeamCount());
  303. }
  304. void CMapGenerator::genZones()
  305. {
  306. getEditManager()->clearTerrain(&rand);
  307. getEditManager()->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions.getWidth(), mapGenOptions.getHeight()));
  308. getEditManager()->drawTerrain(Terrain("grass"), &rand);
  309. auto tmpl = mapGenOptions.getMapTemplate();
  310. zones.clear();
  311. for(const auto & option : tmpl->getZones())
  312. {
  313. auto zone = std::make_shared<CRmgTemplateZone>(this);
  314. zone->setOptions(*option.second.get());
  315. zones[zone->getId()] = zone;
  316. }
  317. CZonePlacer placer(this);
  318. placer.placeZones(&rand);
  319. placer.assignZones();
  320. //add special zone for water
  321. zoneWater.first = zones.size() + 1;
  322. zoneWater.second = std::make_shared<CRmgTemplateZone>(this);
  323. {
  324. rmg::ZoneOptions options;
  325. options.setId(zoneWater.first);
  326. options.setType(ETemplateZoneType::WATER);
  327. zoneWater.second->setOptions(options);
  328. }
  329. logGlobal->info("Zones generated successfully");
  330. }
  331. void CMapGenerator::createWaterTreasures()
  332. {
  333. //add treasures on water
  334. for(auto & treasureInfo : getConfig().waterTreasure)
  335. {
  336. getZoneWater().second->addTreasureInfo(treasureInfo);
  337. }
  338. }
  339. void CMapGenerator::prepareWaterTiles()
  340. {
  341. for(auto & t : zoneWater.second->getTileInfo())
  342. if(shouldBeBlocked(t))
  343. setOccupied(t, ETileType::POSSIBLE);
  344. }
  345. void CMapGenerator::fillZones()
  346. {
  347. //init native town count with 0
  348. for (auto faction : VLC->townh->getAllowedFactions())
  349. zonesPerFaction[faction] = 0;
  350. findZonesForQuestArts();
  351. logGlobal->info("Started filling zones");
  352. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  353. //place main town in the middle
  354. for(auto it : zones)
  355. it.second->initTownType();
  356. //make sure there are some free tiles in the zone
  357. for(auto it : zones)
  358. it.second->initFreeTiles();
  359. for(auto it : zones)
  360. it.second->createBorder(); //once direct connections are done
  361. #ifdef _BETA
  362. dump(false);
  363. #endif
  364. for(auto it : zones)
  365. it.second->createWater(getMapGenOptions().getWaterContent());
  366. zoneWater.second->waterInitFreeTiles();
  367. #ifdef _BETA
  368. dump(false);
  369. #endif
  370. createDirectConnections(); //direct
  371. createConnections2(); //subterranean gates and monoliths
  372. for(auto it : zones)
  373. zoneWater.second->waterConnection(*it.second);
  374. createWaterTreasures();
  375. zoneWater.second->initFreeTiles();
  376. zoneWater.second->fill();
  377. std::vector<std::shared_ptr<CRmgTemplateZone>> treasureZones;
  378. for(auto it : zones)
  379. {
  380. it.second->fill();
  381. if (it.second->getType() == ETemplateZoneType::TREASURE)
  382. treasureZones.push_back(it.second);
  383. }
  384. #ifdef _BETA
  385. dump(false);
  386. #endif
  387. //set apriopriate free/occupied tiles, including blocked underground rock
  388. createObstaclesCommon1();
  389. //set back original terrain for underground zones
  390. for(auto it : zones)
  391. it.second->createObstacles1();
  392. createObstaclesCommon2();
  393. //place actual obstacles matching zone terrain
  394. for(auto it : zones)
  395. it.second->createObstacles2();
  396. zoneWater.second->createObstacles2();
  397. #ifdef _BETA
  398. dump(false);
  399. #endif
  400. #define PRINT_MAP_BEFORE_ROADS false
  401. if (PRINT_MAP_BEFORE_ROADS) //enable to debug
  402. {
  403. std::ofstream out("road_debug.txt");
  404. int levels = map->twoLevel ? 2 : 1;
  405. int width = map->width;
  406. int height = map->height;
  407. for (int k = 0; k < levels; k++)
  408. {
  409. for (int j = 0; j<height; j++)
  410. {
  411. for (int i = 0; i<width; i++)
  412. {
  413. char t = '?';
  414. switch (getTile(int3(i, j, k)).getTileType())
  415. {
  416. case ETileType::FREE:
  417. t = ' '; break;
  418. case ETileType::BLOCKED:
  419. t = '#'; break;
  420. case ETileType::POSSIBLE:
  421. t = '-'; break;
  422. case ETileType::USED:
  423. t = 'O'; break;
  424. }
  425. out << t;
  426. }
  427. out << std::endl;
  428. }
  429. out << std::endl;
  430. }
  431. out << std::endl;
  432. }
  433. for(auto it : zones)
  434. {
  435. it.second->connectRoads(); //draw roads after everything else has been placed
  436. }
  437. //find place for Grail
  438. if(treasureZones.empty())
  439. {
  440. for(auto it : zones)
  441. treasureZones.push_back(it.second);
  442. }
  443. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  444. map->grailPos = *RandomGeneratorUtil::nextItem(*grailZone->getFreePaths(), rand);
  445. logGlobal->info("Zones filled successfully");
  446. }
  447. void CMapGenerator::createObstaclesCommon1()
  448. {
  449. if(map->twoLevel) //underground
  450. {
  451. //negative approach - create rock tiles first, then make sure all accessible tiles have no rock
  452. std::vector<int3> rockTiles;
  453. for(int x = 0; x < map->width; x++)
  454. {
  455. for(int y = 0; y < map->height; y++)
  456. {
  457. int3 tile(x, y, 1);
  458. if (shouldBeBlocked(tile))
  459. {
  460. rockTiles.push_back(tile);
  461. }
  462. }
  463. }
  464. getEditManager()->getTerrainSelection().setSelection(rockTiles);
  465. //collect all rock terrain types
  466. std::vector<Terrain> rockTerrains;
  467. for(auto & terrain : Terrain::Manager::terrains())
  468. if(!terrain.isPassable())
  469. rockTerrains.push_back(terrain);
  470. auto rockTerrain = *RandomGeneratorUtil::nextItem(rockTerrains, rand);
  471. getEditManager()->drawTerrain(rockTerrain, &rand);
  472. }
  473. }
  474. void CMapGenerator::createObstaclesCommon2()
  475. {
  476. if(map->twoLevel)
  477. {
  478. //finally mark rock tiles as occupied, spawn no obstacles there
  479. for(int x = 0; x < map->width; x++)
  480. {
  481. for(int y = 0; y < map->height; y++)
  482. {
  483. int3 tile(x, y, 1);
  484. if(!map->getTile(tile).terType.isPassable())
  485. {
  486. setOccupied(tile, ETileType::USED);
  487. }
  488. }
  489. }
  490. }
  491. //tighten obstacles to improve visuals
  492. for (int i = 0; i < 3; ++i)
  493. {
  494. int blockedTiles = 0;
  495. int freeTiles = 0;
  496. for (int z = 0; z < (map->twoLevel ? 2 : 1); z++)
  497. {
  498. for (int x = 0; x < map->width; x++)
  499. {
  500. for (int y = 0; y < map->height; y++)
  501. {
  502. int3 tile(x, y, z);
  503. if (!isPossible(tile)) //only possible tiles can change
  504. continue;
  505. int blockedNeighbours = 0;
  506. int freeNeighbours = 0;
  507. foreach_neighbour(tile, [this, &blockedNeighbours, &freeNeighbours](int3 &pos)
  508. {
  509. if (this->isBlocked(pos))
  510. blockedNeighbours++;
  511. if (this->isFree(pos))
  512. freeNeighbours++;
  513. });
  514. if (blockedNeighbours > 4)
  515. {
  516. setOccupied(tile, ETileType::BLOCKED);
  517. blockedTiles++;
  518. }
  519. else if (freeNeighbours > 4)
  520. {
  521. setOccupied(tile, ETileType::FREE);
  522. freeTiles++;
  523. }
  524. }
  525. }
  526. }
  527. logGlobal->trace("Set %d tiles to BLOCKED and %d tiles to FREE", blockedTiles, freeTiles);
  528. }
  529. }
  530. void CMapGenerator::findZonesForQuestArts()
  531. {
  532. //we want to place arties in zones that were not yet filled (higher index)
  533. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  534. {
  535. auto zoneA = zones[connection.getZoneA()];
  536. auto zoneB = zones[connection.getZoneB()];
  537. if (zoneA->getId() > zoneB->getId())
  538. {
  539. zoneB->setQuestArtZone(zoneA);
  540. }
  541. else if (zoneA->getId() < zoneB->getId())
  542. {
  543. zoneA->setQuestArtZone(zoneB);
  544. }
  545. }
  546. }
  547. void CMapGenerator::createDirectConnections()
  548. {
  549. bool waterMode = getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  550. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  551. {
  552. auto zoneA = zones[connection.getZoneA()];
  553. auto zoneB = zones[connection.getZoneB()];
  554. //rearrange tiles in random order
  555. const auto & tiles = zoneA->getTileInfo();
  556. int3 guardPos(-1,-1,-1);
  557. int3 posA = zoneA->getPos();
  558. int3 posB = zoneB->getPos();
  559. // auto zoneAid = zoneA->getId();
  560. auto zoneBid = zoneB->getId();
  561. if (posA.z == posB.z)
  562. {
  563. std::vector<int3> middleTiles;
  564. for (const auto& tile : tiles)
  565. {
  566. if (isUsed(tile) || getZoneID(tile)==zoneWater.first) //tiles may be occupied by towns or water
  567. continue;
  568. foreachDirectNeighbour(tile, [tile, &middleTiles, this, zoneBid](int3 & pos) //must be direct since paths also also generated between direct neighbours
  569. {
  570. if(getZoneID(pos) == zoneBid)
  571. middleTiles.push_back(tile);
  572. });
  573. }
  574. //find tiles with minimum manhattan distance from center of the mass of zone border
  575. size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1;
  576. int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0));
  577. middleTile.x /= (si32)tilesCount;
  578. middleTile.y /= (si32)tilesCount;
  579. middleTile.z /= (si32)tilesCount; //TODO: implement division operator for int3?
  580. boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool
  581. {
  582. //choose tiles with both corrdinates in the middle
  583. return lhs.mandist2d(middleTile) < rhs.mandist2d(middleTile);
  584. });
  585. //remove 1/4 tiles from each side - path should cross zone borders at smooth angle
  586. size_t removedCount = tilesCount / 4; //rounded down
  587. middleTiles.erase(middleTiles.end() - removedCount, middleTiles.end());
  588. middleTiles.erase(middleTiles.begin(), middleTiles.begin() + removedCount);
  589. RandomGeneratorUtil::randomShuffle(middleTiles, rand);
  590. for (auto tile : middleTiles)
  591. {
  592. guardPos = tile;
  593. if (guardPos.valid())
  594. {
  595. //zones can make paths only in their own area
  596. zoneA->connectWithCenter(guardPos, true, true);
  597. zoneB->connectWithCenter(guardPos, true, true);
  598. bool monsterPresent = zoneA->addMonster(guardPos, connection.getGuardStrength(), false, true);
  599. zoneB->updateDistances(guardPos); //place next objects away from guard in both zones
  600. //set free tile only after connection is made to the center of the zone
  601. if (!monsterPresent)
  602. setOccupied(guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  603. zoneA->addRoadNode(guardPos);
  604. zoneB->addRoadNode(guardPos);
  605. break; //we're done with this connection
  606. }
  607. }
  608. }
  609. if (!guardPos.valid())
  610. {
  611. if(!waterMode || posA.z != posB.z || !zoneWater.second->waterKeepConnection(connection.getZoneA(), connection.getZoneB()))
  612. connectionsLeft.push_back(connection);
  613. }
  614. }
  615. }
  616. void CMapGenerator::createConnections2()
  617. {
  618. for (auto & connection : connectionsLeft)
  619. {
  620. auto zoneA = zones[connection.getZoneA()];
  621. auto zoneB = zones[connection.getZoneB()];
  622. int3 guardPos(-1, -1, -1);
  623. int3 posA = zoneA->getPos();
  624. int3 posB = zoneB->getPos();
  625. auto strength = connection.getGuardStrength();
  626. if (posA.z != posB.z) //try to place subterranean gates
  627. {
  628. auto sgt = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0)->getTemplates().front();
  629. auto tilesBlockedByObject = sgt.getBlockedOffsets();
  630. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  631. auto gate1 = factory->create(ObjectTemplate());
  632. auto gate2 = factory->create(ObjectTemplate());
  633. while (!guardPos.valid())
  634. {
  635. bool continueOuterLoop = false;
  636. //find common tiles for both zones
  637. auto tileSetA = zoneA->getPossibleTiles(),
  638. tileSetB = zoneB->getPossibleTiles();
  639. std::vector<int3> tilesA(tileSetA.begin(), tileSetA.end()),
  640. tilesB(tileSetB.begin(), tileSetB.end());
  641. std::vector<int3> commonTiles;
  642. auto lambda = [](const int3 & lhs, const int3 & rhs) -> bool
  643. {
  644. //https://stackoverflow.com/questions/45966807/c-invalid-comparator-assert
  645. return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y); //ignore z coordinate
  646. };
  647. //required for set_intersection
  648. boost::sort(tilesA, lambda);
  649. boost::sort(tilesB, lambda);
  650. boost::set_intersection(tilesA, tilesB, std::back_inserter(commonTiles), lambda);
  651. vstd::erase_if(commonTiles, [](const int3 &tile) -> bool
  652. {
  653. return (!tile.x) || (!tile.y); //gates shouldn't go outside map (x = 0) and look bad at the very top (y = 0)
  654. });
  655. if (commonTiles.empty())
  656. break; //nothing more to do
  657. boost::sort(commonTiles, [posA, posB](const int3 &lhs, const int3 &rhs) -> bool
  658. {
  659. //choose tiles which are equidistant to zone centers
  660. return (std::abs<double>(posA.dist2dSQ(lhs) - posB.dist2dSQ(lhs)) < std::abs<double>((posA.dist2dSQ(rhs) - posB.dist2dSQ(rhs))));
  661. });
  662. for (auto tile : commonTiles)
  663. {
  664. tile.z = posA.z;
  665. int3 otherTile = tile;
  666. otherTile.z = posB.z;
  667. float distanceFromA = static_cast<float>(posA.dist2d(tile));
  668. float distanceFromB = static_cast<float>(posB.dist2d(otherTile));
  669. if (distanceFromA > 5 && distanceFromB > 5)
  670. {
  671. if (zoneA->areAllTilesAvailable(gate1, tile, tilesBlockedByObject) &&
  672. zoneB->areAllTilesAvailable(gate2, otherTile, tilesBlockedByObject))
  673. {
  674. if (zoneA->getAccessibleOffset(sgt, tile).valid() && zoneB->getAccessibleOffset(sgt, otherTile).valid())
  675. {
  676. EObjectPlacingResult::EObjectPlacingResult result1 = zoneA->tryToPlaceObjectAndConnectToPath(gate1, tile);
  677. EObjectPlacingResult::EObjectPlacingResult result2 = zoneB->tryToPlaceObjectAndConnectToPath(gate2, otherTile);
  678. if ((result1 == EObjectPlacingResult::SUCCESS) && (result2 == EObjectPlacingResult::SUCCESS))
  679. {
  680. zoneA->placeObject(gate1, tile);
  681. zoneA->guardObject(gate1, strength, true, true);
  682. zoneB->placeObject(gate2, otherTile);
  683. zoneB->guardObject(gate2, strength, true, true);
  684. guardPos = tile; //set to break the loop
  685. break;
  686. }
  687. else if ((result1 == EObjectPlacingResult::SEALED_OFF) || (result2 == EObjectPlacingResult::SEALED_OFF))
  688. {
  689. //sealed-off tiles were blocked, exit inner loop and get another tile set
  690. continueOuterLoop = true;
  691. break;
  692. }
  693. else
  694. continue; //try with another position
  695. }
  696. }
  697. }
  698. }
  699. if (!continueOuterLoop) //we didn't find ANY tile - break outer loop
  700. break;
  701. }
  702. if (!guardPos.valid()) //cleanup? is this safe / enough?
  703. {
  704. delete gate1;
  705. delete gate2;
  706. }
  707. }
  708. if (!guardPos.valid())
  709. {
  710. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, getNextMonlithIndex());
  711. auto teleport1 = factory->create(ObjectTemplate());
  712. auto teleport2 = factory->create(ObjectTemplate());
  713. zoneA->addRequiredObject(teleport1, strength);
  714. zoneB->addRequiredObject(teleport2, strength);
  715. }
  716. }
  717. }
  718. void CMapGenerator::addHeaderInfo()
  719. {
  720. map->version = EMapFormat::VCMI;
  721. map->width = mapGenOptions.getWidth();
  722. map->height = mapGenOptions.getHeight();
  723. map->twoLevel = mapGenOptions.getHasTwoLevels();
  724. map->name = VLC->generaltexth->allTexts[740];
  725. map->description = getMapDescription();
  726. map->difficulty = 1;
  727. addPlayerInfo();
  728. }
  729. void CMapGenerator::checkIsOnMap(const int3& tile) const
  730. {
  731. if (!map->isInTheMap(tile))
  732. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile.toString()));
  733. }
  734. CMapGenerator::Zones & CMapGenerator::getZones()
  735. {
  736. return zones;
  737. }
  738. bool CMapGenerator::isBlocked(const int3 &tile) const
  739. {
  740. checkIsOnMap(tile);
  741. return tiles[tile.x][tile.y][tile.z].isBlocked();
  742. }
  743. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  744. {
  745. checkIsOnMap(tile);
  746. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  747. }
  748. bool CMapGenerator::isPossible(const int3 &tile) const
  749. {
  750. checkIsOnMap(tile);
  751. return tiles[tile.x][tile.y][tile.z].isPossible();
  752. }
  753. bool CMapGenerator::isFree(const int3 &tile) const
  754. {
  755. checkIsOnMap(tile);
  756. return tiles[tile.x][tile.y][tile.z].isFree();
  757. }
  758. bool CMapGenerator::isUsed(const int3 &tile) const
  759. {
  760. checkIsOnMap(tile);
  761. return tiles[tile.x][tile.y][tile.z].isUsed();
  762. }
  763. bool CMapGenerator::isRoad(const int3& tile) const
  764. {
  765. checkIsOnMap(tile);
  766. return tiles[tile.x][tile.y][tile.z].isRoad();
  767. }
  768. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  769. {
  770. checkIsOnMap(tile);
  771. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  772. }
  773. void CMapGenerator::setRoad(const int3& tile, const std::string & roadType)
  774. {
  775. checkIsOnMap(tile);
  776. tiles[tile.x][tile.y][tile.z].setRoadType(roadType);
  777. }
  778. CTileInfo CMapGenerator::getTile(const int3& tile) const
  779. {
  780. checkIsOnMap(tile);
  781. return tiles[tile.x][tile.y][tile.z];
  782. }
  783. TRmgTemplateZoneId CMapGenerator::getZoneID(const int3& tile) const
  784. {
  785. checkIsOnMap(tile);
  786. return zoneColouring[tile.z][tile.x][tile.y];
  787. }
  788. void CMapGenerator::setZoneID(const int3& tile, TRmgTemplateZoneId zid)
  789. {
  790. checkIsOnMap(tile);
  791. zoneColouring[tile.z][tile.x][tile.y] = zid;
  792. }
  793. bool CMapGenerator::isAllowedSpell(SpellID sid) const
  794. {
  795. assert(sid >= 0);
  796. if (sid < map->allowedSpell.size())
  797. {
  798. return map->allowedSpell[sid];
  799. }
  800. else
  801. return false;
  802. }
  803. void CMapGenerator::setNearestObjectDistance(int3 &tile, float value)
  804. {
  805. checkIsOnMap(tile);
  806. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  807. }
  808. float CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  809. {
  810. checkIsOnMap(tile);
  811. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  812. }
  813. int CMapGenerator::getNextMonlithIndex()
  814. {
  815. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  816. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  817. else
  818. return monolithIndex++;
  819. }
  820. int CMapGenerator::getPrisonsRemaning() const
  821. {
  822. return prisonsRemaining;
  823. }
  824. void CMapGenerator::decreasePrisonsRemaining()
  825. {
  826. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  827. }
  828. std::vector<ArtifactID> CMapGenerator::getQuestArtsRemaning() const
  829. {
  830. return questArtifacts;
  831. }
  832. void CMapGenerator::banQuestArt(ArtifactID id)
  833. {
  834. map->allowedArtifact[id] = false;
  835. vstd::erase_if_present (questArtifacts, id);
  836. }
  837. void CMapGenerator::registerZone (TFaction faction)
  838. {
  839. zonesPerFaction[faction]++;
  840. zonesTotal++;
  841. }
  842. ui32 CMapGenerator::getZoneCount(TFaction faction)
  843. {
  844. return zonesPerFaction[faction];
  845. }
  846. ui32 CMapGenerator::getTotalZoneCount() const
  847. {
  848. return zonesTotal;
  849. }
  850. CMapGenerator::Zones::value_type CMapGenerator::getZoneWater() const
  851. {
  852. return zoneWater;
  853. }
  854. void CMapGenerator::dump(bool zoneId)
  855. {
  856. static int id = 0;
  857. std::ofstream out(boost::to_string(boost::format("zone_%d.txt") % id++));
  858. int levels = map->twoLevel ? 2 : 1;
  859. int width = map->width;
  860. int height = map->height;
  861. for (int k = 0; k < levels; k++)
  862. {
  863. for(int j=0; j<height; j++)
  864. {
  865. for (int i=0; i<width; i++)
  866. {
  867. if(zoneId)
  868. {
  869. out << getZoneID(int3(i, j, k));
  870. }
  871. else
  872. {
  873. char t = '?';
  874. switch (getTile(int3(i, j, k)).getTileType())
  875. {
  876. case ETileType::FREE:
  877. t = ' '; break;
  878. case ETileType::BLOCKED:
  879. t = '#'; break;
  880. case ETileType::POSSIBLE:
  881. t = '-'; break;
  882. case ETileType::USED:
  883. t = 'O'; break;
  884. }
  885. out << t;
  886. }
  887. }
  888. out << std::endl;
  889. }
  890. out << std::endl;
  891. }
  892. out << std::endl;
  893. }