CMapGenerator.cpp 23 KB

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