2
0

CMapGenerator.cpp 23 KB

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