CMapGenerator.cpp 23 KB

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