CMapGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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::foreachDiagonaltNeighbour(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() :
  54. mapGenOptions(nullptr), randomSeed(0), editManager(nullptr),
  55. zonesTotal(0), tiles(nullptr), prisonsRemaining(0),
  56. monolithIndex(0)
  57. {
  58. }
  59. void CMapGenerator::initTiles()
  60. {
  61. map->initTerrain();
  62. int width = map->width;
  63. int height = map->height;
  64. int level = map->twoLevel ? 2 : 1;
  65. tiles = new CTileInfo**[width];
  66. for (int i = 0; i < width; ++i)
  67. {
  68. tiles[i] = new CTileInfo*[height];
  69. for (int j = 0; j < height; ++j)
  70. {
  71. tiles[i][j] = new CTileInfo[level];
  72. }
  73. }
  74. zoneColouring.resize(boost::extents[map->twoLevel ? 2 : 1][map->width][map->height]);
  75. }
  76. CMapGenerator::~CMapGenerator()
  77. {
  78. if (tiles)
  79. {
  80. int width = mapGenOptions->getWidth();
  81. int height = mapGenOptions->getHeight();
  82. for (int i=0; i < width; i++)
  83. {
  84. for(int j=0; j < height; j++)
  85. {
  86. delete [] tiles[i][j];
  87. }
  88. delete [] tiles[i];
  89. }
  90. delete [] tiles;
  91. }
  92. }
  93. void CMapGenerator::initPrisonsRemaining()
  94. {
  95. prisonsRemaining = 0;
  96. for (auto isAllowed : map->allowedHeroes)
  97. {
  98. if (isAllowed)
  99. prisonsRemaining++;
  100. }
  101. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions->getPlayerCount()); //so at least 16 heroes will be available for every player
  102. }
  103. void CMapGenerator::initQuestArtsRemaining()
  104. {
  105. for (auto art : VLC->arth->artifacts)
  106. {
  107. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->id) && art->constituentOf.empty()) //don't use parts of combined artifacts
  108. questArtifacts.push_back(art->id);
  109. }
  110. }
  111. std::unique_ptr<CMap> CMapGenerator::generate(CMapGenOptions * mapGenOptions, int randomSeed)
  112. {
  113. this->mapGenOptions = mapGenOptions;
  114. this->randomSeed = randomSeed;
  115. assert(mapGenOptions);
  116. rand.setSeed(this->randomSeed);
  117. mapGenOptions->finalize(rand);
  118. map = make_unique<CMap>();
  119. editManager = map->getEditManager();
  120. try
  121. {
  122. editManager->getUndoManager().setUndoRedoLimit(0);
  123. //FIXME: somehow mapGenOption is nullptr at this point :?
  124. addHeaderInfo();
  125. initTiles();
  126. initPrisonsRemaining();
  127. initQuestArtsRemaining();
  128. genZones();
  129. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  130. fillZones();
  131. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  132. }
  133. catch (rmgException &e)
  134. {
  135. logGlobal->error("Random map generation received exception: %s", e.what());
  136. }
  137. return std::move(map);
  138. }
  139. std::string CMapGenerator::getMapDescription() const
  140. {
  141. assert(mapGenOptions);
  142. assert(map);
  143. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  144. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  145. int monsterStrengthIndex = mapGenOptions->getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  146. std::stringstream ss;
  147. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  148. ", levels %s, players %d, computers %d, water %s, monster %s, VCMI map") % mapGenOptions->getMapTemplate()->getName() %
  149. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  150. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  151. monsterStrengthStr[monsterStrengthIndex]);
  152. for(const auto & pair : mapGenOptions->getPlayersSettings())
  153. {
  154. const auto & pSettings = pair.second;
  155. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  156. {
  157. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  158. }
  159. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  160. {
  161. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  162. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  163. }
  164. }
  165. return ss.str();
  166. }
  167. void CMapGenerator::addPlayerInfo()
  168. {
  169. // Calculate which team numbers exist
  170. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  171. std::array<std::list<int>, 2> teamNumbers;
  172. int teamOffset = 0;
  173. int playerCount = 0;
  174. int teamCount = 0;
  175. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  176. {
  177. if (i == CPHUMAN)
  178. {
  179. playerCount = mapGenOptions->getPlayerCount();
  180. teamCount = mapGenOptions->getTeamCount();
  181. }
  182. else
  183. {
  184. playerCount = mapGenOptions->getCompOnlyPlayerCount();
  185. teamCount = mapGenOptions->getCompOnlyTeamCount();
  186. }
  187. if(playerCount == 0)
  188. {
  189. continue;
  190. }
  191. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  192. int teamCountNorm = teamCount;
  193. if(teamCountNorm == 0)
  194. {
  195. teamCountNorm = playerCount;
  196. }
  197. for(int j = 0; j < teamCountNorm; ++j)
  198. {
  199. for(int k = 0; k < playersPerTeam; ++k)
  200. {
  201. teamNumbers[i].push_back(j + teamOffset);
  202. }
  203. }
  204. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  205. {
  206. teamNumbers[i].push_back(j + teamOffset);
  207. }
  208. teamOffset += teamCountNorm;
  209. }
  210. // Team numbers are assigned randomly to every player
  211. //TODO: allow customize teams in rmg template
  212. for(const auto & pair : mapGenOptions->getPlayersSettings())
  213. {
  214. const auto & pSettings = pair.second;
  215. PlayerInfo player;
  216. player.canComputerPlay = true;
  217. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  218. if (j == CPHUMAN)
  219. {
  220. player.canHumanPlay = true;
  221. }
  222. if (teamNumbers[j].empty())
  223. {
  224. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  225. assert (teamNumbers[j].size());
  226. }
  227. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  228. player.team = TeamID(*itTeam);
  229. teamNumbers[j].erase(itTeam);
  230. map->players[pSettings.getColor().getNum()] = player;
  231. }
  232. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  233. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  234. }
  235. void CMapGenerator::genZones()
  236. {
  237. editManager->clearTerrain(&rand);
  238. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  239. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  240. auto tmpl = mapGenOptions->getMapTemplate();
  241. zones.clear();
  242. for(const auto & option : tmpl->getZones())
  243. {
  244. auto zone = new CRmgTemplateZone();
  245. zone->setOptions(option.second);
  246. zones[zone->getId()] = zone;
  247. //todo: move to CRmgTemplateZone constructor
  248. zone->setGenPtr(this);//immediately set gen pointer before taking any actions on zones
  249. }
  250. CZonePlacer placer(this);
  251. placer.placeZones(mapGenOptions, &rand);
  252. placer.assignZones(mapGenOptions);
  253. logGlobal->info("Zones generated successfully");
  254. }
  255. void CMapGenerator::fillZones()
  256. {
  257. //init native town count with 0
  258. for (auto faction : VLC->townh->getAllowedFactions())
  259. zonesPerFaction[faction] = 0;
  260. findZonesForQuestArts();
  261. logGlobal->info("Started filling zones");
  262. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  263. //place main town in the middle
  264. for (auto it : zones)
  265. it.second->initTownType();
  266. //make sure there are some free tiles in the zone
  267. for (auto it : zones)
  268. it.second->initFreeTiles();
  269. createDirectConnections(); //direct
  270. //make sure all connections are passable before creating borders
  271. for (auto it : zones)
  272. it.second->createBorder(); //once direct connections are done
  273. createConnections2(); //subterranean gates and monoliths
  274. std::vector<CRmgTemplateZone*> treasureZones;
  275. for (auto it : zones)
  276. {
  277. it.second->fill();
  278. if (it.second->getType() == ETemplateZoneType::TREASURE)
  279. treasureZones.push_back(it.second);
  280. }
  281. //set apriopriate free/occupied tiles, including blocked underground rock
  282. createObstaclesCommon1();
  283. //set back original terrain for underground zones
  284. for (auto it : zones)
  285. it.second->createObstacles1();
  286. createObstaclesCommon2();
  287. //place actual obstacles matching zone terrain
  288. for (auto it : zones)
  289. {
  290. it.second->createObstacles2();
  291. }
  292. #define PRINT_MAP_BEFORE_ROADS false
  293. if (PRINT_MAP_BEFORE_ROADS) //enable to debug
  294. {
  295. std::ofstream out("road debug");
  296. int levels = map->twoLevel ? 2 : 1;
  297. int width = map->width;
  298. int height = map->height;
  299. for (int k = 0; k < levels; k++)
  300. {
  301. for (int j = 0; j<height; j++)
  302. {
  303. for (int i = 0; i<width; i++)
  304. {
  305. char t = '?';
  306. switch (getTile(int3(i, j, k)).getTileType())
  307. {
  308. case ETileType::FREE:
  309. t = ' '; break;
  310. case ETileType::BLOCKED:
  311. t = '#'; break;
  312. case ETileType::POSSIBLE:
  313. t = '-'; break;
  314. case ETileType::USED:
  315. t = 'O'; break;
  316. }
  317. out << t;
  318. }
  319. out << std::endl;
  320. }
  321. out << std::endl;
  322. }
  323. out << std::endl;
  324. }
  325. for (auto it : zones)
  326. {
  327. it.second->connectRoads(); //draw roads after everything else has been placed
  328. }
  329. //find place for Grail
  330. if (treasureZones.empty())
  331. {
  332. for (auto it : zones)
  333. treasureZones.push_back(it.second);
  334. }
  335. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  336. map->grailPos = *RandomGeneratorUtil::nextItem(*grailZone->getFreePaths(), rand);
  337. logGlobal->info("Zones filled successfully");
  338. }
  339. void CMapGenerator::createObstaclesCommon1()
  340. {
  341. if (map->twoLevel) //underground
  342. {
  343. //negative approach - create rock tiles first, then make sure all accessible tiles have no rock
  344. std::vector<int3> rockTiles;
  345. for (int x = 0; x < map->width; x++)
  346. {
  347. for (int y = 0; y < map->height; y++)
  348. {
  349. int3 tile(x, y, 1);
  350. if (shouldBeBlocked(tile))
  351. {
  352. rockTiles.push_back(tile);
  353. }
  354. }
  355. }
  356. editManager->getTerrainSelection().setSelection(rockTiles);
  357. editManager->drawTerrain(ETerrainType::ROCK, &rand);
  358. }
  359. }
  360. void CMapGenerator::createObstaclesCommon2()
  361. {
  362. if (map->twoLevel)
  363. {
  364. //finally mark rock tiles as occupied, spawn no obstacles there
  365. for (int x = 0; x < map->width; x++)
  366. {
  367. for (int y = 0; y < map->height; y++)
  368. {
  369. int3 tile(x, y, 1);
  370. if (map->getTile(tile).terType == ETerrainType::ROCK)
  371. {
  372. setOccupied(tile, ETileType::USED);
  373. }
  374. }
  375. }
  376. }
  377. //tighten obstacles to improve visuals
  378. for (int i = 0; i < 3; ++i)
  379. {
  380. int blockedTiles = 0;
  381. int freeTiles = 0;
  382. for (int z = 0; z < (map->twoLevel ? 2 : 1); z++)
  383. {
  384. for (int x = 0; x < map->width; x++)
  385. {
  386. for (int y = 0; y < map->height; y++)
  387. {
  388. int3 tile(x, y, z);
  389. if (!isPossible(tile)) //only possible tiles can change
  390. continue;
  391. int blockedNeighbours = 0;
  392. int freeNeighbours = 0;
  393. foreach_neighbour(tile, [this, &blockedNeighbours, &freeNeighbours](int3 &pos)
  394. {
  395. if (this->isBlocked(pos))
  396. blockedNeighbours++;
  397. if (this->isFree(pos))
  398. freeNeighbours++;
  399. });
  400. if (blockedNeighbours > 4)
  401. {
  402. setOccupied(tile, ETileType::BLOCKED);
  403. blockedTiles++;
  404. }
  405. else if (freeNeighbours > 4)
  406. {
  407. setOccupied(tile, ETileType::FREE);
  408. freeTiles++;
  409. }
  410. }
  411. }
  412. }
  413. logGlobal->trace("Set %d tiles to BLOCKED and %d tiles to FREE", blockedTiles, freeTiles);
  414. }
  415. }
  416. void CMapGenerator::findZonesForQuestArts()
  417. {
  418. //we want to place arties in zones that were not yet filled (higher index)
  419. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  420. {
  421. auto zoneA = zones[connection.getZoneA()];
  422. auto zoneB = zones[connection.getZoneB()];
  423. if (zoneA->getId() > zoneB->getId())
  424. {
  425. zoneB->setQuestArtZone(zoneA);
  426. }
  427. else if (zoneA->getId() < zoneB->getId())
  428. {
  429. zoneA->setQuestArtZone(zoneB);
  430. }
  431. }
  432. }
  433. void CMapGenerator::createDirectConnections()
  434. {
  435. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  436. {
  437. auto zoneA = zones[connection.getZoneA()];
  438. auto zoneB = zones[connection.getZoneB()];
  439. //rearrange tiles in random order
  440. auto tilesCopy = zoneA->getTileInfo();
  441. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  442. int3 guardPos(-1,-1,-1);
  443. auto otherZoneTiles = zoneB->getTileInfo();
  444. int3 posA = zoneA->getPos();
  445. int3 posB = zoneB->getPos();
  446. // auto zoneAid = zoneA->getId();
  447. auto zoneBid = zoneB->getId();
  448. if (posA.z == posB.z)
  449. {
  450. std::vector<int3> middleTiles;
  451. for (auto tile : tilesCopy)
  452. {
  453. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  454. continue;
  455. foreachDirectNeighbour (tile, [&guardPos, tile, &otherZoneTiles, &middleTiles, this, zoneBid](int3 &pos) //must be direct since paths also also generated between direct neighbours
  456. {
  457. if (getZoneID(pos) == zoneBid)
  458. middleTiles.push_back(tile);
  459. });
  460. }
  461. //find tiles with minimum manhattan distance from center of the mass of zone border
  462. size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1;
  463. int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0));
  464. middleTile.x /= tilesCount;
  465. middleTile.y /= tilesCount;
  466. middleTile.z /= tilesCount; //TODO: implement division operator for int3?
  467. boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool
  468. {
  469. //choose tiles with both corrdinates in the middle
  470. return lhs.mandist2d(middleTile) < rhs.mandist2d(middleTile);
  471. });
  472. //remove 1/4 tiles from each side - path should cross zone borders at smooth angle
  473. size_t removedCount = tilesCount / 4; //rounded down
  474. middleTiles.erase(middleTiles.end() - removedCount, middleTiles.end());
  475. middleTiles.erase(middleTiles.begin(), middleTiles.begin() + removedCount);
  476. RandomGeneratorUtil::randomShuffle(middleTiles, rand);
  477. for (auto tile : middleTiles)
  478. {
  479. guardPos = tile;
  480. if (guardPos.valid())
  481. {
  482. //zones can make paths only in their own area
  483. zoneA->connectWithCenter(guardPos, true);
  484. zoneB->connectWithCenter(guardPos, true);
  485. bool monsterPresent = zoneA->addMonster(guardPos, connection.getGuardStrength(), false, true);
  486. zoneB->updateDistances(guardPos); //place next objects away from guard in both zones
  487. //set free tile only after connection is made to the center of the zone
  488. if (!monsterPresent)
  489. setOccupied(guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  490. zoneA->addRoadNode(guardPos);
  491. zoneB->addRoadNode(guardPos);
  492. break; //we're done with this connection
  493. }
  494. }
  495. }
  496. if (!guardPos.valid())
  497. connectionsLeft.push_back(connection);
  498. }
  499. }
  500. void CMapGenerator::createConnections2()
  501. {
  502. for (auto & connection : connectionsLeft)
  503. {
  504. auto zoneA = zones[connection.getZoneA()];
  505. auto zoneB = zones[connection.getZoneB()];
  506. int3 guardPos(-1, -1, -1);
  507. int3 posA = zoneA->getPos();
  508. int3 posB = zoneB->getPos();
  509. auto strength = connection.getGuardStrength();
  510. if (posA.z != posB.z) //try to place subterranean gates
  511. {
  512. auto sgt = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0)->getTemplates().front();
  513. auto tilesBlockedByObject = sgt.getBlockedOffsets();
  514. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  515. auto gate1 = factory->create(ObjectTemplate());
  516. auto gate2 = factory->create(ObjectTemplate());
  517. while (!guardPos.valid())
  518. {
  519. bool continueOuterLoop = false;
  520. //find common tiles for both zones
  521. auto tileSetA = zoneA->getPossibleTiles(),
  522. tileSetB = zoneB->getPossibleTiles();
  523. std::vector<int3> tilesA(tileSetA.begin(), tileSetA.end()),
  524. tilesB(tileSetB.begin(), tileSetB.end());
  525. std::vector<int3> commonTiles;
  526. //required for set_intersection
  527. boost::sort(tilesA);
  528. boost::sort(tilesB);
  529. boost::set_intersection(tilesA, tilesB, std::back_inserter(commonTiles), [](const int3 &lhs, const int3 &rhs) -> bool
  530. {
  531. //ignore z coordinate
  532. if (lhs.x < rhs.x)
  533. return true;
  534. else
  535. return lhs.y < rhs.y;
  536. });
  537. vstd::erase_if(commonTiles, [](const int3 &tile) -> bool
  538. {
  539. return (!tile.x) || (!tile.y); //gates shouldn't go outside map (x = 0) and look bad at the very top (y = 0)
  540. });
  541. if (commonTiles.empty())
  542. break; //nothing more to do
  543. boost::sort(commonTiles, [posA, posB](const int3 &lhs, const int3 &rhs) -> bool
  544. {
  545. //choose tiles which are equidistant to zone centers
  546. return (std::abs<double>(posA.dist2dSQ(lhs) - posB.dist2dSQ(lhs)) < std::abs<double>((posA.dist2dSQ(rhs) - posB.dist2dSQ(rhs))));
  547. });
  548. for (auto tile : commonTiles)
  549. {
  550. tile.z = posA.z;
  551. int3 otherTile = tile;
  552. otherTile.z = posB.z;
  553. float distanceFromA = posA.dist2d(tile);
  554. float distanceFromB = posB.dist2d(otherTile);
  555. if (distanceFromA > 5 && distanceFromB > 5)
  556. {
  557. if (zoneA->areAllTilesAvailable(gate1, tile, tilesBlockedByObject) &&
  558. zoneB->areAllTilesAvailable(gate2, otherTile, tilesBlockedByObject))
  559. {
  560. if (zoneA->getAccessibleOffset(sgt, tile).valid() && zoneB->getAccessibleOffset(sgt, otherTile).valid())
  561. {
  562. EObjectPlacingResult::EObjectPlacingResult result1 = zoneA->tryToPlaceObjectAndConnectToPath(gate1, tile);
  563. EObjectPlacingResult::EObjectPlacingResult result2 = zoneB->tryToPlaceObjectAndConnectToPath(gate2, otherTile);
  564. if ((result1 == EObjectPlacingResult::SUCCESS) && (result2 == EObjectPlacingResult::SUCCESS))
  565. {
  566. zoneA->placeObject(gate1, tile);
  567. zoneA->guardObject(gate1, strength, true, true);
  568. zoneB->placeObject(gate2, otherTile);
  569. zoneB->guardObject(gate2, strength, true, true);
  570. guardPos = tile; //set to break the loop
  571. break;
  572. }
  573. else if ((result1 == EObjectPlacingResult::SEALED_OFF) || (result2 == EObjectPlacingResult::SEALED_OFF))
  574. {
  575. //sealed-off tiles were blocked, exit inner loop and get another tile set
  576. continueOuterLoop = true;
  577. break;
  578. }
  579. else
  580. continue; //try with another position
  581. }
  582. }
  583. }
  584. }
  585. if (!continueOuterLoop) //we didn't find ANY tile - break outer loop
  586. break;
  587. }
  588. if (!guardPos.valid()) //cleanup? is this safe / enough?
  589. {
  590. delete gate1;
  591. delete gate2;
  592. }
  593. }
  594. if (!guardPos.valid())
  595. {
  596. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, getNextMonlithIndex());
  597. auto teleport1 = factory->create(ObjectTemplate());
  598. auto teleport2 = factory->create(ObjectTemplate());
  599. zoneA->addRequiredObject(teleport1, strength);
  600. zoneB->addRequiredObject(teleport2, strength);
  601. }
  602. }
  603. }
  604. void CMapGenerator::addHeaderInfo()
  605. {
  606. map->version = EMapFormat::VCMI;
  607. map->width = mapGenOptions->getWidth();
  608. map->height = mapGenOptions->getHeight();
  609. map->twoLevel = mapGenOptions->getHasTwoLevels();
  610. map->name = VLC->generaltexth->allTexts[740];
  611. map->description = getMapDescription();
  612. map->difficulty = 1;
  613. addPlayerInfo();
  614. }
  615. void CMapGenerator::checkIsOnMap(const int3& tile) const
  616. {
  617. if (!map->isInTheMap(tile))
  618. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile.toString()));
  619. }
  620. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  621. {
  622. return zones;
  623. }
  624. bool CMapGenerator::isBlocked(const int3 &tile) const
  625. {
  626. checkIsOnMap(tile);
  627. return tiles[tile.x][tile.y][tile.z].isBlocked();
  628. }
  629. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  630. {
  631. checkIsOnMap(tile);
  632. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  633. }
  634. bool CMapGenerator::isPossible(const int3 &tile) const
  635. {
  636. checkIsOnMap(tile);
  637. return tiles[tile.x][tile.y][tile.z].isPossible();
  638. }
  639. bool CMapGenerator::isFree(const int3 &tile) const
  640. {
  641. checkIsOnMap(tile);
  642. return tiles[tile.x][tile.y][tile.z].isFree();
  643. }
  644. bool CMapGenerator::isUsed(const int3 &tile) const
  645. {
  646. checkIsOnMap(tile);
  647. return tiles[tile.x][tile.y][tile.z].isUsed();
  648. }
  649. bool CMapGenerator::isRoad(const int3& tile) const
  650. {
  651. checkIsOnMap(tile);
  652. return tiles[tile.x][tile.y][tile.z].isRoad();
  653. }
  654. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  655. {
  656. checkIsOnMap(tile);
  657. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  658. }
  659. void CMapGenerator::setRoad(const int3& tile, ERoadType::ERoadType roadType)
  660. {
  661. checkIsOnMap(tile);
  662. tiles[tile.x][tile.y][tile.z].setRoadType(roadType);
  663. }
  664. CTileInfo CMapGenerator::getTile(const int3& tile) const
  665. {
  666. checkIsOnMap(tile);
  667. return tiles[tile.x][tile.y][tile.z];
  668. }
  669. TRmgTemplateZoneId CMapGenerator::getZoneID(const int3& tile) const
  670. {
  671. checkIsOnMap(tile);
  672. return zoneColouring[tile.z][tile.x][tile.y];
  673. }
  674. void CMapGenerator::setZoneID(const int3& tile, TRmgTemplateZoneId zid)
  675. {
  676. checkIsOnMap(tile);
  677. zoneColouring[tile.z][tile.x][tile.y] = zid;
  678. }
  679. bool CMapGenerator::isAllowedSpell(SpellID sid) const
  680. {
  681. assert(sid >= 0);
  682. if (sid < map->allowedSpell.size())
  683. {
  684. return map->allowedSpell[sid];
  685. }
  686. else
  687. return false;
  688. }
  689. void CMapGenerator::setNearestObjectDistance(int3 &tile, float value)
  690. {
  691. checkIsOnMap(tile);
  692. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  693. }
  694. float CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  695. {
  696. checkIsOnMap(tile);
  697. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  698. }
  699. int CMapGenerator::getNextMonlithIndex()
  700. {
  701. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  702. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  703. else
  704. return monolithIndex++;
  705. }
  706. int CMapGenerator::getPrisonsRemaning() const
  707. {
  708. return prisonsRemaining;
  709. }
  710. void CMapGenerator::decreasePrisonsRemaining()
  711. {
  712. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  713. }
  714. std::vector<ArtifactID> CMapGenerator::getQuestArtsRemaning() const
  715. {
  716. return questArtifacts;
  717. }
  718. void CMapGenerator::banQuestArt(ArtifactID id)
  719. {
  720. map->allowedArtifact[id] = false;
  721. vstd::erase_if_present (questArtifacts, id);
  722. }
  723. void CMapGenerator::registerZone (TFaction faction)
  724. {
  725. zonesPerFaction[faction]++;
  726. zonesTotal++;
  727. }
  728. ui32 CMapGenerator::getZoneCount(TFaction faction)
  729. {
  730. return zonesPerFaction[faction];
  731. }
  732. ui32 CMapGenerator::getTotalZoneCount() const
  733. {
  734. return zonesTotal;
  735. }