CMapGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  245. //place main town in the middle
  246. for (auto it : zones)
  247. it.second->initTownType(this);
  248. //make sure there are some free tiles in the zone
  249. for (auto it : zones)
  250. it.second->initFreeTiles(this);
  251. createDirectConnections(); //direct
  252. //make sure all connections are passable before creating borders
  253. for (auto it : zones)
  254. it.second->createBorder(this); //once direct connections are done
  255. createConnections2(); //subterranean gates and monoliths
  256. std::vector<CRmgTemplateZone*> treasureZones;
  257. for (auto it : zones)
  258. {
  259. it.second->fill(this);
  260. if (it.second->getType() == ETemplateZoneType::TREASURE)
  261. treasureZones.push_back(it.second);
  262. }
  263. //set apriopriate free/occupied tiles, including blocked underground rock
  264. createObstaclesCommon1();
  265. //set back original terrain for underground zones
  266. for (auto it : zones)
  267. it.second->createObstacles1(this);
  268. createObstaclesCommon2();
  269. //place actual obstacles matching zone terrain
  270. for (auto it : zones)
  271. {
  272. it.second->createObstacles2(this);
  273. }
  274. #define PRINT_MAP_BEFORE_ROADS true
  275. if (PRINT_MAP_BEFORE_ROADS) //enable to debug
  276. {
  277. std::ofstream out("road debug");
  278. int levels = map->twoLevel ? 2 : 1;
  279. int width = map->width;
  280. int height = map->height;
  281. for (int k = 0; k < levels; k++)
  282. {
  283. for (int j = 0; j<height; j++)
  284. {
  285. for (int i = 0; i<width; i++)
  286. {
  287. char t = '?';
  288. switch (getTile(int3(i, j, k)).getTileType())
  289. {
  290. case ETileType::FREE:
  291. t = ' '; break;
  292. case ETileType::BLOCKED:
  293. t = '#'; break;
  294. case ETileType::POSSIBLE:
  295. t = '-'; break;
  296. case ETileType::USED:
  297. t = 'O'; break;
  298. }
  299. out << t;
  300. }
  301. out << std::endl;
  302. }
  303. out << std::endl;
  304. }
  305. out << std::endl;
  306. }
  307. for (auto it : zones)
  308. {
  309. it.second->connectRoads(this); //draw roads after everything else has been placed
  310. }
  311. //find place for Grail
  312. if (treasureZones.empty())
  313. {
  314. for (auto it : zones)
  315. treasureZones.push_back(it.second);
  316. }
  317. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  318. map->grailPos = *RandomGeneratorUtil::nextItem(*grailZone->getFreePaths(), rand);
  319. logGlobal->infoStream() << "Zones filled successfully";
  320. }
  321. void CMapGenerator::createObstaclesCommon1()
  322. {
  323. if (map->twoLevel) //underground
  324. {
  325. //negative approach - create rock tiles first, then make sure all accessible tiles have no rock
  326. std::vector<int3> rockTiles;
  327. for (int x = 0; x < map->width; x++)
  328. {
  329. for (int y = 0; y < map->height; y++)
  330. {
  331. int3 tile(x, y, 1);
  332. if (shouldBeBlocked(tile))
  333. {
  334. rockTiles.push_back(tile);
  335. }
  336. }
  337. }
  338. editManager->getTerrainSelection().setSelection(rockTiles);
  339. editManager->drawTerrain(ETerrainType::ROCK, &rand);
  340. }
  341. }
  342. void CMapGenerator::createObstaclesCommon2()
  343. {
  344. if (map->twoLevel)
  345. {
  346. //finally mark rock tiles as occupied, spawn no obstacles there
  347. for (int x = 0; x < map->width; x++)
  348. {
  349. for (int y = 0; y < map->height; y++)
  350. {
  351. int3 tile(x, y, 1);
  352. if (map->getTile(tile).terType == ETerrainType::ROCK)
  353. {
  354. setOccupied(tile, ETileType::USED);
  355. }
  356. }
  357. }
  358. }
  359. //tighten obstacles to improve visuals
  360. for (int i = 0; i < 3; ++i)
  361. {
  362. int blockedTiles = 0;
  363. int freeTiles = 0;
  364. for (int z = 0; z < (map->twoLevel ? 2 : 1); z++)
  365. {
  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, z);
  371. if (!isPossible(tile)) //only possible tiles can change
  372. continue;
  373. int blockedNeighbours = 0;
  374. int freeNeighbours = 0;
  375. foreach_neighbour(tile, [this, &blockedNeighbours, &freeNeighbours](int3 &pos)
  376. {
  377. if (this->isBlocked(pos))
  378. blockedNeighbours++;
  379. if (this->isFree(pos))
  380. freeNeighbours++;
  381. });
  382. if (blockedNeighbours > 4)
  383. {
  384. setOccupied(tile, ETileType::BLOCKED);
  385. blockedTiles++;
  386. }
  387. else if (freeNeighbours > 4)
  388. {
  389. setOccupied(tile, ETileType::FREE);
  390. freeTiles++;
  391. }
  392. }
  393. }
  394. }
  395. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  396. }
  397. }
  398. void CMapGenerator::findZonesForQuestArts()
  399. {
  400. //we want to place arties in zones that were not yet filled (higher index)
  401. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  402. {
  403. auto zoneA = connection.getZoneA();
  404. auto zoneB = connection.getZoneB();
  405. if (zoneA->getId() > zoneB->getId())
  406. {
  407. zoneB->setQuestArtZone(zoneA);
  408. }
  409. else if (zoneA->getId() < zoneB->getId())
  410. {
  411. zoneA->setQuestArtZone(zoneB);
  412. }
  413. }
  414. }
  415. void CMapGenerator::createDirectConnections()
  416. {
  417. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  418. {
  419. auto zoneA = connection.getZoneA();
  420. auto zoneB = connection.getZoneB();
  421. //rearrange tiles in random order
  422. auto tilesCopy = zoneA->getTileInfo();
  423. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  424. int3 guardPos(-1,-1,-1);
  425. auto otherZoneTiles = zoneB->getTileInfo();
  426. int3 posA = zoneA->getPos();
  427. int3 posB = zoneB->getPos();
  428. // auto zoneAid = zoneA->getId();
  429. auto zoneBid = zoneB->getId();
  430. if (posA.z == posB.z)
  431. {
  432. std::vector<int3> middleTiles;
  433. for (auto tile : tilesCopy)
  434. {
  435. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  436. continue;
  437. foreachDirectNeighbour (tile, [&guardPos, tile, &otherZoneTiles, &middleTiles, this, zoneBid](int3 &pos) //must be direct since paths also also generated between direct neighbours
  438. {
  439. if (getZoneID(pos) == zoneBid)
  440. middleTiles.push_back(tile);
  441. });
  442. }
  443. //find tiles with minimum manhattan distance from center of the mass of zone border
  444. size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1;
  445. int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0));
  446. middleTile.x /= tilesCount;
  447. middleTile.y /= tilesCount;
  448. middleTile.z /= tilesCount; //TODO: implement division operator for int3?
  449. boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool
  450. {
  451. //choose tiles with both corrdinates in the middle
  452. return lhs.mandist2d(middleTile) < rhs.mandist2d(middleTile);
  453. });
  454. //remove 1/4 tiles from each side - path should cross zone borders at smooth angle
  455. size_t removedCount = tilesCount / 4; //rounded down
  456. middleTiles.erase(middleTiles.end() - removedCount, middleTiles.end());
  457. middleTiles.erase(middleTiles.begin(), middleTiles.begin() + removedCount);
  458. RandomGeneratorUtil::randomShuffle(middleTiles, rand);
  459. for (auto tile : middleTiles)
  460. {
  461. guardPos = tile;
  462. if (guardPos.valid())
  463. {
  464. //zones can make paths only in their own area
  465. zoneA->connectWithCenter(this, guardPos, true);
  466. zoneB->connectWithCenter(this, guardPos, true);
  467. bool monsterPresent = zoneA->addMonster(this, guardPos, connection.getGuardStrength(), false, true);
  468. zoneB->updateDistances(this, guardPos); //place next objects away from guard in both zones
  469. //set free tile only after connection is made to the center of the zone
  470. if (!monsterPresent)
  471. setOccupied(guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  472. zoneA->addRoadNode(guardPos);
  473. zoneB->addRoadNode(guardPos);
  474. break; //we're done with this connection
  475. }
  476. }
  477. }
  478. if (!guardPos.valid())
  479. connectionsLeft.push_back(connection);
  480. }
  481. }
  482. void CMapGenerator::createConnections2()
  483. {
  484. for (auto & connection : connectionsLeft)
  485. {
  486. auto zoneA = connection.getZoneA();
  487. auto zoneB = connection.getZoneB();
  488. int3 guardPos(-1, -1, -1);
  489. int3 posA = zoneA->getPos();
  490. int3 posB = zoneB->getPos();
  491. auto strength = connection.getGuardStrength();
  492. if (posA.z != posB.z) //try to place subterranean gates
  493. {
  494. auto sgt = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0)->getTemplates().front();
  495. auto tilesBlockedByObject = sgt.getBlockedOffsets();
  496. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  497. auto gate1 = factory->create(ObjectTemplate());
  498. auto gate2 = factory->create(ObjectTemplate());
  499. while (!guardPos.valid())
  500. {
  501. bool continueOuterLoop = false;
  502. //find common tiles for both zones
  503. auto tileSetA = zoneA->getPossibleTiles(),
  504. tileSetB = zoneB->getPossibleTiles();
  505. std::vector<int3> tilesA(tileSetA.begin(), tileSetA.end()),
  506. tilesB(tileSetB.begin(), tileSetB.end());
  507. std::vector<int3> commonTiles;
  508. //required for set_intersection
  509. boost::sort(tilesA);
  510. boost::sort(tilesB);
  511. boost::set_intersection(tilesA, tilesB, std::back_inserter(commonTiles), [](const int3 &lhs, const int3 &rhs) -> bool
  512. {
  513. //ignore z coordinate
  514. if (lhs.x < rhs.x)
  515. return true;
  516. else
  517. return lhs.y < rhs.y;
  518. });
  519. vstd::erase_if(commonTiles, [](const int3 &tile) -> bool
  520. {
  521. return (!tile.x) || (!tile.y); //gates shouldn't go outside map (x = 0) and look bad at the very top (y = 0)
  522. });
  523. if (commonTiles.empty())
  524. break; //nothing more to do
  525. boost::sort(commonTiles, [posA, posB](const int3 &lhs, const int3 &rhs) -> bool
  526. {
  527. //choose tiles which are equidistant to zone centers
  528. return (std::abs<double>(posA.dist2dSQ(lhs) - posB.dist2dSQ(lhs)) < std::abs<double>((posA.dist2dSQ(rhs) - posB.dist2dSQ(rhs))));
  529. });
  530. for (auto tile : commonTiles)
  531. {
  532. tile.z = posA.z;
  533. int3 otherTile = tile;
  534. otherTile.z = posB.z;
  535. float distanceFromA = posA.dist2d(tile);
  536. float distanceFromB = posB.dist2d(otherTile);
  537. if (distanceFromA > 5 && distanceFromB > 5)
  538. {
  539. if (zoneA->areAllTilesAvailable(this, gate1, tile, tilesBlockedByObject) &&
  540. zoneB->areAllTilesAvailable(this, gate2, otherTile, tilesBlockedByObject))
  541. {
  542. if (zoneA->getAccessibleOffset(this, sgt, tile).valid() && zoneB->getAccessibleOffset(this, sgt, otherTile).valid())
  543. {
  544. EObjectPlacingResult::EObjectPlacingResult result1 = zoneA->tryToPlaceObjectAndConnectToPath(this, gate1, tile);
  545. EObjectPlacingResult::EObjectPlacingResult result2 = zoneB->tryToPlaceObjectAndConnectToPath(this, gate2, otherTile);
  546. if ((result1 == EObjectPlacingResult::SUCCESS) && (result2 == EObjectPlacingResult::SUCCESS))
  547. {
  548. zoneA->placeObject(this, gate1, tile);
  549. zoneA->guardObject(this, gate1, strength, true, true);
  550. zoneB->placeObject(this, gate2, otherTile);
  551. zoneB->guardObject(this, gate2, strength, true, true);
  552. guardPos = tile; //set to break the loop
  553. break;
  554. }
  555. else if ((result1 == EObjectPlacingResult::SEALED_OFF) || (result2 == EObjectPlacingResult::SEALED_OFF))
  556. {
  557. //sealed-off tiles were blocked, exit inner loop and get another tile set
  558. continueOuterLoop = true;
  559. break;
  560. }
  561. else
  562. continue; //try with another position
  563. }
  564. }
  565. }
  566. }
  567. if (!continueOuterLoop) //we didn't find ANY tile - break outer loop
  568. break;
  569. }
  570. if (!guardPos.valid()) //cleanup? is this safe / enough?
  571. {
  572. delete gate1;
  573. delete gate2;
  574. }
  575. }
  576. if (!guardPos.valid())
  577. {
  578. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, getNextMonlithIndex());
  579. auto teleport1 = factory->create(ObjectTemplate());
  580. auto teleport2 = factory->create(ObjectTemplate());
  581. zoneA->addRequiredObject(teleport1, strength);
  582. zoneB->addRequiredObject(teleport2, strength);
  583. }
  584. }
  585. }
  586. void CMapGenerator::addHeaderInfo()
  587. {
  588. map->version = EMapFormat::VCMI;
  589. map->width = mapGenOptions->getWidth();
  590. map->height = mapGenOptions->getHeight();
  591. map->twoLevel = mapGenOptions->getHasTwoLevels();
  592. map->name = VLC->generaltexth->allTexts[740];
  593. map->description = getMapDescription();
  594. map->difficulty = 1;
  595. addPlayerInfo();
  596. }
  597. void CMapGenerator::checkIsOnMap(const int3& tile) const
  598. {
  599. if (!map->isInTheMap(tile))
  600. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  601. }
  602. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  603. {
  604. return zones;
  605. }
  606. bool CMapGenerator::isBlocked(const int3 &tile) const
  607. {
  608. checkIsOnMap(tile);
  609. return tiles[tile.x][tile.y][tile.z].isBlocked();
  610. }
  611. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  612. {
  613. checkIsOnMap(tile);
  614. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  615. }
  616. bool CMapGenerator::isPossible(const int3 &tile) const
  617. {
  618. checkIsOnMap(tile);
  619. return tiles[tile.x][tile.y][tile.z].isPossible();
  620. }
  621. bool CMapGenerator::isFree(const int3 &tile) const
  622. {
  623. checkIsOnMap(tile);
  624. return tiles[tile.x][tile.y][tile.z].isFree();
  625. }
  626. bool CMapGenerator::isUsed(const int3 &tile) const
  627. {
  628. checkIsOnMap(tile);
  629. return tiles[tile.x][tile.y][tile.z].isUsed();
  630. }
  631. bool CMapGenerator::isRoad(const int3& tile) const
  632. {
  633. checkIsOnMap(tile);
  634. return tiles[tile.x][tile.y][tile.z].isRoad();
  635. }
  636. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  637. {
  638. checkIsOnMap(tile);
  639. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  640. }
  641. void CMapGenerator::setRoad(const int3& tile, ERoadType::ERoadType roadType)
  642. {
  643. checkIsOnMap(tile);
  644. tiles[tile.x][tile.y][tile.z].setRoadType(roadType);
  645. }
  646. CTileInfo CMapGenerator::getTile(const int3& tile) const
  647. {
  648. checkIsOnMap(tile);
  649. return tiles[tile.x][tile.y][tile.z];
  650. }
  651. TRmgTemplateZoneId CMapGenerator::getZoneID(const int3& tile) const
  652. {
  653. checkIsOnMap(tile);
  654. return zoneColouring[tile.z][tile.x][tile.y];
  655. }
  656. void CMapGenerator::setZoneID(const int3& tile, TRmgTemplateZoneId zid)
  657. {
  658. checkIsOnMap(tile);
  659. zoneColouring[tile.z][tile.x][tile.y] = zid;
  660. }
  661. bool CMapGenerator::isAllowedSpell(SpellID sid) const
  662. {
  663. assert(sid >= 0);
  664. if (sid < map->allowedSpell.size())
  665. {
  666. return map->allowedSpell[sid];
  667. }
  668. else
  669. return false;
  670. }
  671. void CMapGenerator::setNearestObjectDistance(int3 &tile, float value)
  672. {
  673. checkIsOnMap(tile);
  674. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  675. }
  676. float CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  677. {
  678. checkIsOnMap(tile);
  679. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  680. }
  681. int CMapGenerator::getNextMonlithIndex()
  682. {
  683. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  684. {
  685. //logGlobal->errorStream() << boost::to_string(boost::format("RMG Error! There is no Monolith Two Way with index %d available!") % monolithIndex);
  686. //monolithIndex++;
  687. //return VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size() - 1;
  688. //TODO: interrupt map generation and report error
  689. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  690. }
  691. else
  692. return monolithIndex++;
  693. }
  694. int CMapGenerator::getPrisonsRemaning() const
  695. {
  696. return prisonsRemaining;
  697. }
  698. void CMapGenerator::decreasePrisonsRemaining()
  699. {
  700. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  701. }
  702. std::vector<ArtifactID> CMapGenerator::getQuestArtsRemaning() const
  703. {
  704. return questArtifacts;
  705. }
  706. void CMapGenerator::banQuestArt(ArtifactID id)
  707. {
  708. map->allowedArtifact[id] = false;
  709. vstd::erase_if_present (questArtifacts, id);
  710. }
  711. void CMapGenerator::registerZone (TFaction faction)
  712. {
  713. zonesPerFaction[faction]++;
  714. zonesTotal++;
  715. }
  716. ui32 CMapGenerator::getZoneCount(TFaction faction)
  717. {
  718. return zonesPerFaction[faction];
  719. }
  720. ui32 CMapGenerator::getTotalZoneCount() const
  721. {
  722. return zonesTotal;
  723. }