CMapGenerator.cpp 28 KB

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