CRmgTemplateZone.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330
  1. /*
  2. * CRmgTemplateZone.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 "CRmgTemplateZone.h"
  12. #include "../mapping/CMapEditManager.h"
  13. #include "../mapping/CMap.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../CTownHandler.h"
  16. #include "../CCreatureHandler.h"
  17. #include "../spells/CSpellHandler.h" //for choosing random spells
  18. #include "../mapObjects/CommonConstructors.h"
  19. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  20. #include "../mapObjects/CGPandoraBox.h"
  21. #include "../mapObjects/CRewardableObject.h"
  22. class CMap;
  23. class CMapEditManager;
  24. //class CGObjectInstance;
  25. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  26. {
  27. }
  28. int CRmgTemplateZone::CTownInfo::getTownCount() const
  29. {
  30. return townCount;
  31. }
  32. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  33. {
  34. if(value < 0)
  35. throw rmgException("Negative value for town count not allowed.");
  36. townCount = value;
  37. }
  38. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  39. {
  40. return castleCount;
  41. }
  42. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  43. {
  44. if(value < 0)
  45. throw rmgException("Negative value for castle count not allowed.");
  46. castleCount = value;
  47. }
  48. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  49. {
  50. return townDensity;
  51. }
  52. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  53. {
  54. if(value < 0)
  55. throw rmgException("Negative value for town density not allowed.");
  56. townDensity = value;
  57. }
  58. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  59. {
  60. return castleDensity;
  61. }
  62. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  63. {
  64. if(value < 0)
  65. throw rmgException("Negative value for castle density not allowed.");
  66. castleDensity = value;
  67. }
  68. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  69. {
  70. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  71. }
  72. float CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(float value)
  77. {
  78. nearestObjectDistance = std::max<float>(0, value); //never negative (or unitialized)
  79. }
  80. bool CTileInfo::shouldBeBlocked() const
  81. {
  82. return occupied == ETileType::BLOCKED;
  83. }
  84. bool CTileInfo::isBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  87. }
  88. bool CTileInfo::isPossible() const
  89. {
  90. return occupied == ETileType::POSSIBLE;
  91. }
  92. bool CTileInfo::isFree() const
  93. {
  94. return occupied == ETileType::FREE;
  95. }
  96. bool CTileInfo::isUsed() const
  97. {
  98. return occupied == ETileType::USED;
  99. }
  100. void CTileInfo::setOccupied(ETileType::ETileType value)
  101. {
  102. occupied = value;
  103. }
  104. ETileType::ETileType CTileInfo::getTileType() const
  105. {
  106. return occupied;
  107. }
  108. ETerrainType CTileInfo::getTerrainType() const
  109. {
  110. return terrain;
  111. }
  112. void CTileInfo::setTerrainType(ETerrainType value)
  113. {
  114. terrain = value;
  115. }
  116. CRmgTemplateZone::CRmgTemplateZone() :
  117. id(0),
  118. type(ETemplateZoneType::PLAYER_START),
  119. size(1),
  120. townsAreSameType(false),
  121. matchTerrainToTown(true),
  122. townType(ETownType::NEUTRAL),
  123. terrainType (ETerrainType::GRASS),
  124. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  125. minGuardedValue(0),
  126. questArtZone(nullptr)
  127. {
  128. terrainTypes = getDefaultTerrainTypes();
  129. }
  130. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  131. {
  132. return id;
  133. }
  134. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  135. {
  136. if(value <= 0)
  137. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  138. id = value;
  139. }
  140. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  141. {
  142. return type;
  143. }
  144. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  145. {
  146. type = value;
  147. }
  148. int CRmgTemplateZone::getSize() const
  149. {
  150. return size;
  151. }
  152. void CRmgTemplateZone::setSize(int value)
  153. {
  154. if(value <= 0)
  155. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  156. size = value;
  157. }
  158. boost::optional<int> CRmgTemplateZone::getOwner() const
  159. {
  160. return owner;
  161. }
  162. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  163. {
  164. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  165. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  166. owner = value;
  167. }
  168. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  169. {
  170. return playerTowns;
  171. }
  172. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  173. {
  174. playerTowns = value;
  175. }
  176. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  177. {
  178. return neutralTowns;
  179. }
  180. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  181. {
  182. neutralTowns = value;
  183. }
  184. bool CRmgTemplateZone::getTownsAreSameType() const
  185. {
  186. return townsAreSameType;
  187. }
  188. void CRmgTemplateZone::setTownsAreSameType(bool value)
  189. {
  190. townsAreSameType = value;
  191. }
  192. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  193. {
  194. return townTypes;
  195. }
  196. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  197. {
  198. townTypes = value;
  199. }
  200. void CRmgTemplateZone::setMonsterTypes(const std::set<TFaction> & value)
  201. {
  202. monsterTypes = value;
  203. }
  204. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  205. {
  206. std::set<TFaction> defaultTowns;
  207. auto towns = VLC->townh->getDefaultAllowed();
  208. for(int i = 0; i < towns.size(); ++i)
  209. {
  210. if(towns[i]) defaultTowns.insert(i);
  211. }
  212. return defaultTowns;
  213. }
  214. bool CRmgTemplateZone::getMatchTerrainToTown() const
  215. {
  216. return matchTerrainToTown;
  217. }
  218. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  219. {
  220. matchTerrainToTown = value;
  221. }
  222. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  223. {
  224. return terrainTypes;
  225. }
  226. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  227. {
  228. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  229. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  230. terrainTypes = value;
  231. }
  232. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  233. {
  234. std::set<ETerrainType> terTypes;
  235. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  236. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  237. for (auto & allowedTerType : allowedTerTypes)
  238. terTypes.insert(allowedTerType);
  239. return terTypes;
  240. }
  241. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  242. {
  243. mines[res] = amount;
  244. }
  245. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  246. {
  247. return mines;
  248. }
  249. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  250. {
  251. connections.push_back (otherZone);
  252. }
  253. void CRmgTemplateZone::setQuestArtZone(CRmgTemplateZone * otherZone)
  254. {
  255. questArtZone = otherZone;
  256. }
  257. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  258. {
  259. return connections;
  260. }
  261. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  262. {
  263. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  264. zoneMonsterStrength = val;
  265. }
  266. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  267. {
  268. treasureInfo.push_back(info);
  269. }
  270. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  271. {
  272. return treasureInfo;
  273. }
  274. std::set<int3>* CRmgTemplateZone::getFreePaths()
  275. {
  276. return &freePaths;
  277. }
  278. float3 CRmgTemplateZone::getCenter() const
  279. {
  280. return center;
  281. }
  282. void CRmgTemplateZone::setCenter(const float3 &f)
  283. {
  284. //limit boundaries to (0,1) square
  285. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  286. }
  287. bool CRmgTemplateZone::pointIsIn(int x, int y)
  288. {
  289. return true;
  290. }
  291. int3 CRmgTemplateZone::getPos() const
  292. {
  293. return pos;
  294. }
  295. void CRmgTemplateZone::setPos(const int3 &Pos)
  296. {
  297. pos = Pos;
  298. }
  299. void CRmgTemplateZone::addTile (const int3 &pos)
  300. {
  301. tileinfo.insert(pos);
  302. }
  303. std::set<int3> CRmgTemplateZone::getTileInfo () const
  304. {
  305. return tileinfo;
  306. }
  307. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  308. {
  309. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  310. //for (auto tile : tileinfo)
  311. //{
  312. // if (tile.dist2d(this->pos) > distance)
  313. // {
  314. // gen->setOccupied(tile, ETileType::USED);
  315. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  316. // }
  317. //}
  318. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  319. {
  320. return tile.dist2d(this->pos) > distance;
  321. });
  322. }
  323. void CRmgTemplateZone::clearTiles()
  324. {
  325. tileinfo.clear();
  326. }
  327. void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
  328. {
  329. vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
  330. {
  331. return gen->isPossible(tile);
  332. });
  333. if (freePaths.empty())
  334. freePaths.insert(pos); //zone must have at least one free tile where other paths go - for instance in the center
  335. }
  336. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  337. {
  338. for (auto tile : tileinfo)
  339. {
  340. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  341. {
  342. if (!vstd::contains(this->tileinfo, pos))
  343. {
  344. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  345. {
  346. if (gen->isPossible(pos))
  347. gen->setOccupied (pos, ETileType::BLOCKED);
  348. });
  349. }
  350. });
  351. }
  352. }
  353. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  354. {
  355. for (auto tile : tileinfo)
  356. {
  357. if (gen->isFree(tile))
  358. freePaths.insert(tile);
  359. }
  360. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  361. std::set<int3> possibleTiles;
  362. std::set<int3> tilesToClear; //will be set clear
  363. std::set<int3> tilesToIgnore; //will be erased in this iteration
  364. //the more treasure density, the greater distance between paths. Scaling is experimental.
  365. int totalDensity = 0;
  366. for (auto ti : treasureInfo)
  367. totalDensity =+ ti.density;
  368. const float minDistance = 10 * 10; //squared
  369. for (auto tile : tileinfo)
  370. {
  371. if (gen->isFree(tile))
  372. clearedTiles.push_back(tile);
  373. else if (gen->isPossible(tile))
  374. possibleTiles.insert(tile);
  375. }
  376. assert (clearedTiles.size()); //this should come from zone connections
  377. if (type != ETemplateZoneType::JUNCTION)
  378. {
  379. //junction is not fractalized, has only one straight path
  380. //everything else remains blocked
  381. while (possibleTiles.size())
  382. {
  383. //link tiles in random order
  384. std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
  385. RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
  386. for (auto tileToMakePath : tilesToMakePath)
  387. {
  388. //find closest free tile
  389. float currentDistance = 1e10;
  390. int3 closestTile(-1, -1, -1);
  391. for (auto clearTile : clearedTiles)
  392. {
  393. float distance = tileToMakePath.dist2dSQ(clearTile);
  394. if (distance < currentDistance)
  395. {
  396. currentDistance = distance;
  397. closestTile = clearTile;
  398. }
  399. if (currentDistance <= minDistance)
  400. {
  401. //this tile is close enough. Forget about it and check next one
  402. tilesToIgnore.insert(tileToMakePath);
  403. break;
  404. }
  405. }
  406. //if tiles is not close enough, make path to it
  407. if (currentDistance > minDistance)
  408. {
  409. crunchPath(gen, tileToMakePath, closestTile, id, &tilesToClear);
  410. break; //next iteration - use already cleared tiles
  411. }
  412. }
  413. for (auto tileToClear : tilesToClear)
  414. {
  415. //move cleared tiles from one set to another
  416. clearedTiles.push_back(tileToClear);
  417. vstd::erase_if_present(possibleTiles, tileToClear);
  418. }
  419. for (auto tileToClear : tilesToIgnore)
  420. {
  421. //these tiles are already connected, ignore them
  422. vstd::erase_if_present(possibleTiles, tileToClear);
  423. }
  424. if (tilesToClear.empty()) //nothing else can be done (?)
  425. break;
  426. tilesToClear.clear(); //empty this container
  427. tilesToIgnore.clear();
  428. }
  429. }
  430. for (auto tile : clearedTiles)
  431. {
  432. freePaths.insert(tile);
  433. }
  434. //now block most distant tiles away from passages
  435. float blockDistance = minDistance * 0.25f;
  436. for (auto tile : tileinfo)
  437. {
  438. if (!gen->isPossible(tile))
  439. continue;
  440. bool closeTileFound = false;
  441. for (auto clearTile : freePaths)
  442. {
  443. float distance = tile.dist2dSQ(clearTile);
  444. if (distance < blockDistance)
  445. {
  446. closeTileFound = true;
  447. break;
  448. }
  449. }
  450. if (!closeTileFound) //this tile is far enough from passages
  451. gen->setOccupied(tile, ETileType::BLOCKED);
  452. }
  453. #define PRINT_FRACTALIZED_MAP false
  454. if (PRINT_FRACTALIZED_MAP) //enable to debug
  455. {
  456. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  457. int levels = gen->map->twoLevel ? 2 : 1;
  458. int width = gen->map->width;
  459. int height = gen->map->height;
  460. for (int k = 0; k < levels; k++)
  461. {
  462. for(int j=0; j<height; j++)
  463. {
  464. for (int i=0; i<width; i++)
  465. {
  466. char t = '?';
  467. switch (gen->getTile(int3(i, j, k)).getTileType())
  468. {
  469. case ETileType::FREE:
  470. t = ' '; break;
  471. case ETileType::BLOCKED:
  472. t = '#'; break;
  473. case ETileType::POSSIBLE:
  474. t = '-'; break;
  475. case ETileType::USED:
  476. t = 'O'; break;
  477. }
  478. out << t;
  479. }
  480. out << std::endl;
  481. }
  482. out << std::endl;
  483. }
  484. out << std::endl;
  485. }
  486. //logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  487. }
  488. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  489. {
  490. /*
  491. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  492. do not leave zone border
  493. */
  494. bool result = false;
  495. bool end = false;
  496. int3 currentPos = src;
  497. float distance = currentPos.dist2dSQ (dst);
  498. while (!end)
  499. {
  500. if (currentPos == dst)
  501. {
  502. result = true;
  503. break;
  504. }
  505. auto lastDistance = distance;
  506. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  507. {
  508. if (!result) //not sure if lambda is worth it...
  509. {
  510. if (pos == dst)
  511. {
  512. result = true;
  513. end = true;
  514. }
  515. if (pos.dist2dSQ (dst) < distance)
  516. {
  517. if (!gen->isBlocked(pos))
  518. {
  519. if (vstd::contains (tileinfo, pos))
  520. {
  521. if (gen->isPossible(pos))
  522. {
  523. gen->setOccupied (pos, ETileType::FREE);
  524. if (clearedTiles)
  525. clearedTiles->insert(pos);
  526. currentPos = pos;
  527. distance = currentPos.dist2dSQ (dst);
  528. }
  529. else if (gen->isFree(pos))
  530. {
  531. end = true;
  532. result = true;
  533. }
  534. }
  535. }
  536. }
  537. }
  538. });
  539. int3 anotherPos(-1, -1, -1);
  540. if (!(result || distance < lastDistance)) //we do not advance, use more advaced pathfinding algorithm?
  541. {
  542. //try any nearby tiles, even if its not closer than current
  543. float lastDistance = 2 * distance; //start with significantly larger value
  544. gen->foreach_neighbour(currentPos, [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  545. {
  546. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  547. {
  548. if (vstd::contains(tileinfo, pos))
  549. {
  550. if (gen->isPossible(pos))
  551. {
  552. if (clearedTiles)
  553. clearedTiles->insert(pos);
  554. anotherPos = pos;
  555. lastDistance = currentPos.dist2dSQ(dst);
  556. }
  557. }
  558. }
  559. });
  560. if (anotherPos.valid())
  561. {
  562. if (clearedTiles)
  563. clearedTiles->insert(anotherPos);
  564. gen->setOccupied(anotherPos, ETileType::FREE);
  565. currentPos = anotherPos;
  566. }
  567. }
  568. if (!(result || distance < lastDistance || anotherPos.valid()))
  569. {
  570. logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  571. break;
  572. }
  573. }
  574. return result;
  575. }
  576. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  577. {
  578. requiredObjects.push_back(std::make_pair(obj, strength));
  579. }
  580. void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
  581. {
  582. closeObjects.push_back(std::make_pair(obj, strength));
  583. }
  584. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  585. {
  586. //precalculate actual (randomized) monster strength based on this post
  587. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  588. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  589. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  590. static const int value1[] = {2500, 1500, 1000, 500, 0};
  591. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  592. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  593. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  594. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  595. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  596. strength = strength1 + strength2;
  597. if (strength < 2000)
  598. return false; //no guard at all
  599. CreatureID creId = CreatureID::NONE;
  600. int amount = 0;
  601. std::vector<CreatureID> possibleCreatures;
  602. for (auto cre : VLC->creh->creatures)
  603. {
  604. if (cre->special)
  605. continue;
  606. if (!vstd::contains(monsterTypes, cre->faction))
  607. continue;
  608. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100
  609. {
  610. possibleCreatures.push_back(cre->idNumber);
  611. }
  612. }
  613. if (possibleCreatures.size())
  614. {
  615. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  616. amount = strength / VLC->creh->creatures[creId]->AIValue;
  617. if (amount >= 4)
  618. amount *= gen->rand.nextDouble(0.75, 1.25);
  619. }
  620. else //just pick any available creature
  621. {
  622. creId = CreatureID(132); //Azure Dragon
  623. amount = strength / VLC->creh->creatures[creId]->AIValue;
  624. }
  625. auto guard = new CGCreature();
  626. guard->ID = Obj::MONSTER;
  627. guard->subID = creId;
  628. guard->character = CGCreature::HOSTILE;
  629. auto hlp = new CStackInstance(creId, amount);
  630. //will be set during initialization
  631. guard->putStack(SlotID(0), hlp);
  632. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  633. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  634. placeObject(gen, guard, pos);
  635. if (clearSurroundingTiles)
  636. {
  637. //do not spawn anything near monster
  638. gen->foreach_neighbour (pos, [gen](int3 pos)
  639. {
  640. if (gen->isPossible(pos))
  641. gen->setOccupied(pos, ETileType::FREE);
  642. });
  643. }
  644. return true;
  645. }
  646. bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  647. {
  648. CTreasurePileInfo info;
  649. std::map<int3, CGObjectInstance *> treasures;
  650. std::set<int3> boundary;
  651. int3 guardPos (-1,-1,-1);
  652. info.nextTreasurePos = pos;
  653. int maxValue = treasureInfo.max;
  654. int minValue = treasureInfo.min;
  655. ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
  656. int currentValue = 0;
  657. CGObjectInstance * object = nullptr;
  658. while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable
  659. {
  660. treasures[info.nextTreasurePos] = nullptr;
  661. for (auto treasurePos : treasures)
  662. {
  663. gen->foreach_neighbour(treasurePos.first, [gen, &boundary](int3 pos)
  664. {
  665. boundary.insert(pos);
  666. });
  667. }
  668. for (auto treasurePos : treasures)
  669. {
  670. //leaving only boundary around objects
  671. vstd::erase_if_present(boundary, treasurePos.first);
  672. }
  673. for (auto tile : boundary)
  674. {
  675. //we can't extend boundary anymore
  676. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  677. break;
  678. }
  679. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  680. if (!oi.value) //0 value indicates no object
  681. {
  682. vstd::erase_if_present(treasures, info.nextTreasurePos);
  683. break;
  684. }
  685. else
  686. {
  687. object = oi.generateObject();
  688. //remove from possible objects
  689. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  690. assert (oiptr != possibleObjects.end());
  691. oiptr->maxPerZone--;
  692. if (!oiptr->maxPerZone)
  693. possibleObjects.erase(oiptr);
  694. //update treasure pile area
  695. int3 visitablePos = info.nextTreasurePos;
  696. if (oi.templ.isVisitableFromTop())
  697. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  698. else
  699. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  700. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  701. {
  702. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  703. info.occupiedPositions.insert(blockPos);
  704. info.blockedPositions.insert(blockPos);
  705. }
  706. info.occupiedPositions.insert(visitablePos);
  707. currentValue += oi.value;
  708. treasures[info.nextTreasurePos] = object;
  709. //now find place for next object
  710. int3 placeFound(-1,-1,-1);
  711. //randomize next position from among possible ones
  712. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  713. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  714. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  715. {
  716. return lhs.y < rhs.y;
  717. };
  718. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  719. for (auto tile : boundaryCopy)
  720. {
  721. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  722. {
  723. bool here = true;
  724. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  725. {
  726. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  727. here = false;
  728. });
  729. if (here)
  730. {
  731. placeFound = tile;
  732. break;
  733. }
  734. }
  735. }
  736. if (placeFound.valid())
  737. info.nextTreasurePos = placeFound;
  738. else
  739. break; //no more place to add any objects
  740. }
  741. }
  742. if (treasures.size())
  743. {
  744. //find object closest to zone center, then connect it to the middle of the zone
  745. int3 closestFreeTile (-1,-1,-1);
  746. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  747. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  748. else
  749. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  750. int3 closestTile = int3(-1,-1,-1);
  751. float minDistance = 1e10;
  752. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  753. {
  754. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  755. {
  756. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  757. minDistance = closestFreeTile.dist2d(visitablePos);
  758. }
  759. }
  760. if (!closestTile.valid())
  761. {
  762. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  763. {
  764. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  765. {
  766. closestTile = visitablePos;
  767. minDistance = closestFreeTile.dist2d(visitablePos);
  768. }
  769. }
  770. }
  771. assert (closestTile.valid());
  772. for (auto tile : info.occupiedPositions)
  773. {
  774. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  775. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  776. }
  777. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  778. {
  779. //we can't connect this pile, just block it off and start over
  780. for (auto treasure : treasures)
  781. {
  782. if (gen->isPossible(treasure.first))
  783. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  784. }
  785. return true;
  786. }
  787. //update boundary around our objects, including knowledge about objects visitable from bottom
  788. boundary.clear();
  789. for (auto tile : info.visitableFromBottomPositions)
  790. {
  791. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  792. {
  793. if (pos.y >= tile.y) //don't block these objects from above
  794. boundary.insert(pos);
  795. });
  796. }
  797. for (auto tile : info.visitableFromTopPositions)
  798. {
  799. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  800. {
  801. boundary.insert(pos);
  802. });
  803. }
  804. bool isPileGuarded = currentValue >= minGuardedValue;
  805. for (auto tile : boundary) //guard must be standing there
  806. {
  807. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  808. {
  809. guardPos = tile;
  810. break;
  811. }
  812. }
  813. if (guardPos.valid())
  814. {
  815. for (auto treasure : treasures)
  816. {
  817. int3 visitableOffset = treasure.second->getVisitableOffset();
  818. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  819. }
  820. if (addMonster(gen, guardPos, currentValue, false))
  821. {//block only if the object is guarded
  822. for (auto tile : boundary)
  823. {
  824. if (gen->isPossible(tile))
  825. gen->setOccupied(tile, ETileType::BLOCKED);
  826. }
  827. //do not spawn anything near monster
  828. gen->foreach_neighbour(guardPos, [gen](int3 pos)
  829. {
  830. if (gen->isPossible(pos))
  831. gen->setOccupied(pos, ETileType::FREE);
  832. });
  833. }
  834. else //mo monster in this pile, make some free space (needed?)
  835. {
  836. for (auto tile : boundary)
  837. if (gen->isPossible(tile))
  838. gen->setOccupied(tile, ETileType::FREE);
  839. }
  840. }
  841. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  842. {
  843. for (auto treasure : treasures)
  844. {
  845. if (gen->isPossible(treasure.first))
  846. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  847. delete treasure.second;
  848. }
  849. }
  850. return true;
  851. }
  852. else //we did not place eveyrthing successfully
  853. return false;
  854. }
  855. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  856. {
  857. //FIXME: handle case that this player is not present -> towns should be set to neutral
  858. int totalTowns = 0;
  859. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  860. {
  861. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  862. for (auto tile : town->getBlockedPos())
  863. {
  864. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  865. {
  866. if (gen->isPossible(pos))
  867. {
  868. gen->setOccupied(pos, ETileType::FREE);
  869. }
  870. });
  871. }
  872. };
  873. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  874. {
  875. for (int i = 0; i < count; i++)
  876. {
  877. auto town = new CGTownInstance();
  878. town->ID = Obj::TOWN;
  879. if (this->townsAreSameType)
  880. town->subID = townType;
  881. else
  882. {
  883. if (townTypes.size())
  884. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  885. else
  886. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  887. }
  888. town->tempOwner = player;
  889. if (hasFort)
  890. town->builtBuildings.insert(BuildingID::FORT);
  891. town->builtBuildings.insert(BuildingID::DEFAULT);
  892. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  893. {
  894. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  895. town->possibleSpells.push_back(spell->id);
  896. }
  897. if (!totalTowns)
  898. {
  899. //first town in zone sets the facton of entire zone
  900. town->subID = townType;
  901. //register MAIN town of zone
  902. gen->registerZone(town->subID);
  903. //first town in zone goes in the middle
  904. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  905. cutPathAroundTown(town);
  906. }
  907. else
  908. addRequiredObject (town);
  909. totalTowns++;
  910. }
  911. };
  912. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  913. {
  914. //set zone types to player faction, generate main town
  915. logGlobal->infoStream() << "Preparing playing zone";
  916. int player_id = *owner - 1;
  917. auto & playerInfo = gen->map->players[player_id];
  918. if (playerInfo.canAnyonePlay())
  919. {
  920. PlayerColor player(player_id);
  921. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  922. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  923. {
  924. if (townTypes.size())
  925. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  926. else
  927. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  928. }
  929. auto town = new CGTownInstance();
  930. town->ID = Obj::TOWN;
  931. town->subID = townType;
  932. town->tempOwner = player;
  933. town->builtBuildings.insert(BuildingID::FORT);
  934. town->builtBuildings.insert(BuildingID::DEFAULT);
  935. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  936. {
  937. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  938. town->possibleSpells.push_back(spell->id);
  939. }
  940. //towns are big objects and should be centered around visitable position
  941. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  942. cutPathAroundTown(town);
  943. totalTowns++;
  944. //register MAIN town of zone only
  945. gen->registerZone (town->subID);
  946. logGlobal->traceStream() << "Fill player info " << player_id;
  947. // Update player info
  948. playerInfo.allowedFactions.clear();
  949. playerInfo.allowedFactions.insert (townType);
  950. playerInfo.hasMainTown = true;
  951. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  952. playerInfo.generateHeroAtMainTown = true;
  953. //now create actual towns
  954. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  955. addNewTowns (playerTowns.getTownCount(), false, player);
  956. //requiredObjects.push_back(town);
  957. }
  958. else
  959. {
  960. type = ETemplateZoneType::TREASURE;
  961. if (townTypes.size())
  962. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  963. else
  964. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  965. }
  966. }
  967. else //no player
  968. {
  969. if (townTypes.size())
  970. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  971. else
  972. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  973. }
  974. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  975. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  976. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  977. {
  978. //25% chance for neutral
  979. if (gen->rand.nextInt(1, 100) <= 25)
  980. {
  981. townType = ETownType::NEUTRAL;
  982. }
  983. else
  984. {
  985. if (townTypes.size())
  986. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  987. else if (monsterTypes.size())
  988. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  989. }
  990. }
  991. }
  992. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  993. {
  994. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  995. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  996. else
  997. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  998. //TODO: allow new types of terrain?
  999. if (pos.z)
  1000. {
  1001. if (terrainType != ETerrainType::LAVA)
  1002. terrainType = ETerrainType::SUBTERRANEAN;
  1003. }
  1004. else
  1005. {
  1006. if (terrainType == ETerrainType::SUBTERRANEAN)
  1007. terrainType = ETerrainType::DIRT;
  1008. }
  1009. paintZoneTerrain (gen, terrainType);
  1010. }
  1011. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  1012. {
  1013. std::vector<int3> tiles;
  1014. for (auto tile : tileinfo)
  1015. {
  1016. tiles.push_back (tile);
  1017. }
  1018. gen->editManager->getTerrainSelection().setSelection(tiles);
  1019. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1020. }
  1021. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  1022. {
  1023. std::vector<Res::ERes> required_mines;
  1024. required_mines.push_back(Res::ERes::WOOD);
  1025. required_mines.push_back(Res::ERes::ORE);
  1026. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1027. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1028. for (const auto & res : woodOre)
  1029. {
  1030. for (int i = 0; i < mines[res]; i++)
  1031. {
  1032. auto mine = new CGMine();
  1033. mine->ID = Obj::MINE;
  1034. mine->subID = static_cast<si32>(res);
  1035. mine->producedResource = res;
  1036. mine->producedQuantity = mine->defaultResProduction();
  1037. addCloseObject(mine, 1500);
  1038. }
  1039. }
  1040. for (const auto & res : preciousResources)
  1041. {
  1042. for (int i = 0; i < mines[res]; i++)
  1043. {
  1044. auto mine = new CGMine();
  1045. mine->ID = Obj::MINE;
  1046. mine->subID = static_cast<si32>(res);
  1047. mine->producedResource = res;
  1048. mine->producedQuantity = mine->defaultResProduction();
  1049. addRequiredObject(mine, 3500);
  1050. }
  1051. }
  1052. for (int i = 0; i < mines[Res::GOLD]; i++)
  1053. {
  1054. auto mine = new CGMine();
  1055. mine->ID = Obj::MINE;
  1056. mine->subID = static_cast<si32>(Res::GOLD);
  1057. mine->producedResource = Res::GOLD;
  1058. mine->producedQuantity = mine->defaultResProduction();
  1059. addRequiredObject(mine, 7000);
  1060. }
  1061. return true;
  1062. }
  1063. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1064. {
  1065. logGlobal->traceStream() << "Creating required objects";
  1066. for(const auto &obj : requiredObjects)
  1067. {
  1068. int3 pos;
  1069. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  1070. {
  1071. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  1072. //TODO CLEANUP!
  1073. return false;
  1074. }
  1075. placeObject (gen, obj.first, pos);
  1076. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1077. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1078. }
  1079. for (const auto &obj : closeObjects)
  1080. {
  1081. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1082. // smallest distance to zone center, greatest distance to nearest object
  1083. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1084. {
  1085. return (this->pos.dist2dSQ(lhs) * 0.5f - gen->getNearestObjectDistance(lhs)) < (this->pos.dist2dSQ(rhs) * 0.5f - gen->getNearestObjectDistance(rhs));
  1086. };
  1087. boost::sort (tiles, isCloser);
  1088. setTemplateForObject(gen, obj.first);
  1089. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1090. bool result = false;
  1091. for (auto tile : tiles)
  1092. {
  1093. //object must be accessible from at least one surounding tile
  1094. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile, tilesBlockedByObject))
  1095. continue;
  1096. //avoid borders
  1097. if (gen->isPossible(tile))
  1098. {
  1099. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1100. {
  1101. placeObject(gen, obj.first, tile);
  1102. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1103. result = true;
  1104. break;
  1105. }
  1106. }
  1107. }
  1108. if (!result)
  1109. {
  1110. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1111. //TODO CLEANUP!
  1112. return false;
  1113. }
  1114. }
  1115. return true;
  1116. }
  1117. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1118. {
  1119. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  1120. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1121. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1122. minGuardedValue = minGuardedValues[monsterStrength];
  1123. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1124. {
  1125. return lhs.max > rhs.max;
  1126. };
  1127. //place biggest treasures first at large distance, place smaller ones inbetween
  1128. boost::sort(treasureInfo, valueComparator);
  1129. int totalDensity = 0;
  1130. for (auto t : treasureInfo)
  1131. {
  1132. //discard objects with too high value to be ever placed
  1133. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  1134. {
  1135. return oi.value > t.max;
  1136. });
  1137. totalDensity += t.density;
  1138. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1139. //also, normalize it to zone count - higher count means relatively smaller zones
  1140. //this is squared distance for optimization purposes
  1141. const double minDistance = std::max<float>((125.f / totalDensity), 2);
  1142. //distance lower than 2 causes objects to overlap and crash
  1143. do {
  1144. //optimization - don't check tiles which are not allowed
  1145. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1146. {
  1147. return !gen->isPossible(tile);
  1148. });
  1149. int3 pos;
  1150. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1151. if (!findPlaceForTreasurePile(gen, minDistance, pos, t.min))
  1152. {
  1153. break;
  1154. }
  1155. createTreasurePile(gen, pos, minDistance, t);
  1156. } while (true);
  1157. }
  1158. }
  1159. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1160. {
  1161. typedef std::vector<ObjectTemplate> obstacleVector;
  1162. //obstacleVector possibleObstacles;
  1163. std::map <ui8, obstacleVector> obstaclesBySize;
  1164. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1165. std::vector<obstaclePair> possibleObstacles;
  1166. //get all possible obstacles for this terrain
  1167. for (auto primaryID : VLC->objtypeh->knownObjects())
  1168. {
  1169. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1170. {
  1171. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1172. if (handler->isStaticObject())
  1173. {
  1174. for (auto temp : handler->getTemplates())
  1175. {
  1176. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1177. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. for (auto o : obstaclesBySize)
  1183. {
  1184. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1185. }
  1186. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1187. {
  1188. return p1.first > p2.first; //bigger obstacles first
  1189. });
  1190. auto sel = gen->editManager->getTerrainSelection();
  1191. sel.clearSelection();
  1192. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1193. {
  1194. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1195. int3 obstaclePos = tile + temp.getBlockMapOffset();
  1196. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1197. {
  1198. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1199. placeObject(gen, obj, obstaclePos, false);
  1200. return true;
  1201. }
  1202. return false;
  1203. };
  1204. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1205. for (auto tile : boost::adaptors::reverse(tileinfo))
  1206. {
  1207. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1208. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1209. {
  1210. //start from biggets obstacles
  1211. for (int i = 0; i < possibleObstacles.size(); i++)
  1212. {
  1213. if (tryToPlaceObstacleHere(tile, i))
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. }
  1219. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1220. {
  1221. initTerrainType(gen);
  1222. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1223. addAllPossibleObjects (gen);
  1224. placeMines(gen);
  1225. createRequiredObjects(gen);
  1226. fractalize(gen); //after required objects are created and linked with their own paths
  1227. createTreasures(gen);
  1228. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1229. return true;
  1230. }
  1231. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1232. {
  1233. float best_distance = 0;
  1234. bool result = false;
  1235. bool needsGuard = value > minGuardedValue;
  1236. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1237. for(auto tile : possibleTiles)
  1238. {
  1239. auto dist = gen->getNearestObjectDistance(tile);
  1240. if ((dist >= min_dist) && (dist > best_distance))
  1241. {
  1242. bool allTilesAvailable = true;
  1243. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1244. {
  1245. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1246. {
  1247. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1248. }
  1249. });
  1250. if (allTilesAvailable)
  1251. {
  1252. best_distance = dist;
  1253. pos = tile;
  1254. result = true;
  1255. }
  1256. }
  1257. }
  1258. if (result)
  1259. {
  1260. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1261. }
  1262. return result;
  1263. }
  1264. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1265. {
  1266. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1267. return false;
  1268. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1269. for (auto blockingTile : tilesBlockedByObject)
  1270. {
  1271. int3 t = pos + blockingTile;
  1272. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1273. {
  1274. return false; //if at least one tile is not possible, object can't be placed here
  1275. }
  1276. }
  1277. return true;
  1278. }
  1279. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1280. {
  1281. bool accessible = false;
  1282. for (int x = -1; x < 2; x++)
  1283. {
  1284. for (int y = -1; y <2; y++)
  1285. {
  1286. if (x && y) //check only if object is visitable from another tile
  1287. {
  1288. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1289. if (!vstd::contains(tilesBlockedByObject, offset))
  1290. {
  1291. int3 nearbyPos = tile + offset;
  1292. if (gen->map->isInTheMap(nearbyPos))
  1293. {
  1294. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1295. accessible = true;
  1296. }
  1297. }
  1298. }
  1299. };
  1300. }
  1301. return accessible;
  1302. }
  1303. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1304. {
  1305. if (obj->appearance.id == Obj::NO_OBJ)
  1306. {
  1307. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1308. if (templates.empty())
  1309. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1310. obj->appearance = templates.front();
  1311. }
  1312. }
  1313. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1314. {
  1315. for (auto blockingTile : tilesBlockedByObject)
  1316. {
  1317. int3 t = tile + blockingTile;
  1318. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1319. {
  1320. //if at least one tile is not possible, object can't be placed here
  1321. return false;
  1322. }
  1323. }
  1324. return true;
  1325. }
  1326. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1327. {
  1328. //we need object apperance to deduce free tile
  1329. setTemplateForObject(gen, obj);
  1330. //si32 min_dist = sqrt(tileinfo.size()/density);
  1331. int best_distance = 0;
  1332. bool result = false;
  1333. //si32 w = gen->map->width;
  1334. //si32 h = gen->map->height;
  1335. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1336. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1337. for (auto tile : tileinfo)
  1338. {
  1339. //object must be accessible from at least one surounding tile
  1340. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1341. continue;
  1342. auto ti = gen->getTile(tile);
  1343. auto dist = ti.getNearestObjectDistance();
  1344. //avoid borders
  1345. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1346. {
  1347. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1348. {
  1349. best_distance = dist;
  1350. pos = tile;
  1351. result = true;
  1352. }
  1353. }
  1354. }
  1355. if (result)
  1356. {
  1357. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1358. }
  1359. return result;
  1360. }
  1361. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1362. {
  1363. if (!gen->map->isInTheMap(pos))
  1364. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1365. object->pos = pos;
  1366. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1367. throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
  1368. for (auto tile : object->getBlockedPos())
  1369. {
  1370. if (!gen->map->isInTheMap(tile))
  1371. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1372. }
  1373. if (object->appearance.id == Obj::NO_OBJ)
  1374. {
  1375. auto terrainType = gen->map->getTile(pos).terType;
  1376. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1377. if (templates.empty())
  1378. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
  1379. object->appearance = templates.front();
  1380. }
  1381. gen->editManager->insertObject(object, pos);
  1382. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1383. }
  1384. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1385. {
  1386. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1387. checkAndPlaceObject (gen, object, pos);
  1388. auto points = object->getBlockedPos();
  1389. if (object->isVisitable())
  1390. points.insert(pos + object->getVisitableOffset());
  1391. points.insert(pos);
  1392. for(auto p : points)
  1393. {
  1394. if (gen->map->isInTheMap(p))
  1395. {
  1396. gen->setOccupied(p, ETileType::USED);
  1397. }
  1398. }
  1399. if (updateDistance)
  1400. {
  1401. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1402. {
  1403. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1404. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1405. }
  1406. }
  1407. if (object->ID == Obj::SEER_HUT) //debug
  1408. {
  1409. CGSeerHut * sh = dynamic_cast<CGSeerHut *>(object);
  1410. auto artid = sh->quest->m5arts.front();
  1411. logGlobal->warnStream() << boost::format("Placed Seer Hut at %s, quest artifact %d is %s") % object->pos % artid % VLC->arth->artifacts[artid]->Name();
  1412. }
  1413. }
  1414. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1415. {
  1416. placeObject(gen, object, pos);
  1417. guardObject(gen, object, str, zoneGuard);
  1418. }
  1419. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1420. {
  1421. //get all tiles from which this object can be accessed
  1422. int3 visitable = object->visitablePos();
  1423. std::vector<int3> tiles;
  1424. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1425. gen->foreach_neighbour(visitable, [&](int3& pos)
  1426. {
  1427. if (gen->isPossible(pos))
  1428. {
  1429. if (!vstd::contains(tilesBlockedByObject, pos))
  1430. {
  1431. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1432. {
  1433. tiles.push_back(pos);
  1434. }
  1435. }
  1436. };
  1437. });
  1438. return tiles;
  1439. }
  1440. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1441. {
  1442. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1443. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1444. int3 guardTile(-1,-1,-1);
  1445. for (auto tile : tiles)
  1446. {
  1447. //crunching path may fail if center of the zone is directly over wide object
  1448. //make sure object is accessible before surrounding it with blocked tiles
  1449. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1450. {
  1451. guardTile = tile;
  1452. break;
  1453. }
  1454. }
  1455. if (!guardTile.valid())
  1456. {
  1457. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1458. return false;
  1459. }
  1460. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1461. {
  1462. for (auto pos : tiles)
  1463. {
  1464. if (!gen->isFree(pos))
  1465. gen->setOccupied(pos, ETileType::BLOCKED);
  1466. }
  1467. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1468. {
  1469. if (gen->isPossible(pos))
  1470. gen->setOccupied (pos, ETileType::FREE);
  1471. });
  1472. gen->setOccupied (guardTile, ETileType::USED);
  1473. }
  1474. else //allow no guard or other object in front of this object
  1475. {
  1476. for (auto tile : tiles)
  1477. if (gen->isPossible(tile))
  1478. gen->setOccupied (tile, ETileType::FREE);
  1479. }
  1480. return true;
  1481. }
  1482. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1483. {
  1484. //int objectsVisitableFromBottom = 0; //for debug
  1485. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1486. ui32 total = 0;
  1487. //calculate actual treasure value range based on remaining value
  1488. ui32 maxVal = desiredValue - currentValue;
  1489. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1490. //roulette wheel
  1491. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1492. {
  1493. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1494. {
  1495. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1496. int3 newVisitablePos = info.nextTreasurePos;
  1497. if (!oi.templ.isVisitableFromTop())
  1498. {
  1499. //objectsVisitableFromBottom++;
  1500. //there must be free tiles under object
  1501. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1502. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1503. continue;
  1504. }
  1505. //NOTE: y coordinate grows downwards
  1506. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1507. {
  1508. bool fitsHere = false;
  1509. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1510. {
  1511. for (auto tile : info.visitableFromTopPositions)
  1512. {
  1513. int3 actualTile = tile + newVisitableOffset;
  1514. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1515. {
  1516. fitsHere = true;
  1517. break;
  1518. }
  1519. }
  1520. for (auto tile : info.visitableFromBottomPositions)
  1521. {
  1522. int3 actualTile = tile + newVisitableOffset;
  1523. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1524. {
  1525. fitsHere = true;
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. else //if new object is not visitable from top, it must be accessible from below or side
  1531. {
  1532. for (auto tile : info.visitableFromTopPositions)
  1533. {
  1534. int3 actualTile = tile + newVisitableOffset;
  1535. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1536. {
  1537. fitsHere = true;
  1538. break;
  1539. }
  1540. }
  1541. for (auto tile : info.visitableFromBottomPositions)
  1542. {
  1543. int3 actualTile = tile + newVisitableOffset;
  1544. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1545. {
  1546. fitsHere = true;
  1547. break;
  1548. }
  1549. }
  1550. }
  1551. if (!fitsHere)
  1552. continue;
  1553. }
  1554. //now check blockmap, including our already reserved pile area
  1555. bool fitsBlockmap = true;
  1556. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1557. blockedOffsets.insert (newVisitableOffset);
  1558. for (auto blockingTile : blockedOffsets)
  1559. {
  1560. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1561. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1562. {
  1563. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1564. break;
  1565. }
  1566. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1567. {
  1568. fitsBlockmap = false;
  1569. break;
  1570. }
  1571. }
  1572. if (!fitsBlockmap)
  1573. continue;
  1574. total += oi.probability;
  1575. //assert (oi.value > 0);
  1576. tresholds.push_back (std::make_pair (total, oi));
  1577. }
  1578. }
  1579. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1580. if (tresholds.empty())
  1581. {
  1582. ObjectInfo oi;
  1583. //Generate pandora Box with gold if the value is extremely high
  1584. if (minValue > 20000) //we don't have object valuable enough
  1585. {
  1586. oi.generateObject = [minValue]() -> CGObjectInstance *
  1587. {
  1588. auto obj = new CGPandoraBox();
  1589. obj->ID = Obj::PANDORAS_BOX;
  1590. obj->subID = 0;
  1591. obj->resources[Res::GOLD] = minValue;
  1592. return obj;
  1593. };
  1594. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1595. oi.value = minValue;
  1596. oi.probability = 0;
  1597. }
  1598. else //generate empty object with 0 value if the value if we can't spawn anything
  1599. {
  1600. oi.generateObject = [gen]() -> CGObjectInstance *
  1601. {
  1602. return nullptr;
  1603. };
  1604. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1605. oi.value = 0; // this field is checked to determine no object
  1606. oi.probability = 0;
  1607. }
  1608. return oi;
  1609. }
  1610. else
  1611. {
  1612. int r = gen->rand.nextInt (1, total);
  1613. for (auto t : tresholds)
  1614. {
  1615. if (r <= t.first)
  1616. return t.second;
  1617. }
  1618. assert (0); //we should never be here
  1619. }
  1620. //FIXME: control reaches end of non-void function. Missing return?
  1621. }
  1622. void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
  1623. {
  1624. ObjectInfo oi;
  1625. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1626. int numZones = gen->getZones().size();
  1627. std::vector<CCreature *> creatures; //native creatures for this zone
  1628. for (auto cre : VLC->creh->creatures)
  1629. {
  1630. if (!cre->special && cre->faction == townType)
  1631. {
  1632. creatures.push_back(cre);
  1633. }
  1634. }
  1635. for (auto primaryID : VLC->objtypeh->knownObjects())
  1636. {
  1637. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1638. {
  1639. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1640. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1641. {
  1642. for (auto temp : handler->getTemplates())
  1643. {
  1644. if (temp.canBePlacedAt(terrainType))
  1645. {
  1646. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1647. {
  1648. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1649. };
  1650. auto rmgInfo = handler->getRMGInfo();
  1651. oi.value = rmgInfo.value;
  1652. oi.probability = rmgInfo.rarity;
  1653. oi.templ = temp;
  1654. oi.maxPerZone = rmgInfo.zoneLimit;
  1655. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1656. possibleObjects.push_back(oi);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. }
  1662. //prisons
  1663. //levels 1, 5, 10, 20, 30
  1664. static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
  1665. static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
  1666. for (int i = 0; i < 5; i++)
  1667. {
  1668. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1669. {
  1670. auto obj = new CGHeroInstance;
  1671. obj->ID = Obj::PRISON;
  1672. std::vector<ui32> possibleHeroes;
  1673. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1674. {
  1675. if (gen->map->allowedHeroes[j])
  1676. possibleHeroes.push_back(j);
  1677. }
  1678. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1679. obj->subID = hid; //will be initialized later
  1680. obj->exp = prisonExp[i];
  1681. obj->setOwner(PlayerColor::NEUTRAL);
  1682. gen->map->allowedHeroes[hid] = false; //ban this hero
  1683. gen->decreasePrisonsRemaining();
  1684. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1685. return obj;
  1686. };
  1687. oi.setTemplate(Obj::PRISON, 0, terrainType);
  1688. oi.value = prisonValues[i];
  1689. oi.probability = 30;
  1690. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1691. possibleObjects.push_back(oi);
  1692. }
  1693. //all following objects are unlimited
  1694. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1695. //dwellings
  1696. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1697. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1698. static int elementalConfluxROE[] = { 7, 13, 16, 47 };
  1699. for (int i = 0; i < 4; i++)
  1700. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1701. for (auto secondaryID : subObjects)
  1702. {
  1703. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1704. auto creatures = dwellingHandler->getProducedCreatures();
  1705. if (creatures.empty())
  1706. continue;
  1707. auto cre = creatures.front();
  1708. if (cre->faction == townType)
  1709. {
  1710. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1711. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1712. oi.probability = 40;
  1713. for (auto temp : dwellingHandler->getTemplates())
  1714. {
  1715. if (temp.canBePlacedAt(terrainType))
  1716. {
  1717. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1718. {
  1719. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1720. //dwellingHandler->configureObject(obj, gen->rand);
  1721. obj->tempOwner = PlayerColor::NEUTRAL;
  1722. return obj;
  1723. };
  1724. oi.templ = temp;
  1725. possibleObjects.push_back(oi);
  1726. }
  1727. }
  1728. }
  1729. }
  1730. static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
  1731. for (int i = 0; i < 5; i++)
  1732. {
  1733. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1734. {
  1735. auto obj = new CGArtifact();
  1736. obj->ID = Obj::SPELL_SCROLL;
  1737. obj->subID = 0;
  1738. std::vector<SpellID> out;
  1739. //TODO: unify with cb->getAllowedSpells?
  1740. for (ui32 spellid = 0; spellid < gen->map->allowedSpell.size(); spellid++) //spellh size appears to be greater (?)
  1741. {
  1742. const CSpell *spell = SpellID(spellid).toSpell();
  1743. if (gen->map->allowedSpell[spell->id] && spell->level == i + 1)
  1744. {
  1745. out.push_back(spell->id);
  1746. }
  1747. }
  1748. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1749. gen->map->addNewArtifactInstance(a);
  1750. obj->storedArtifact = a;
  1751. return obj;
  1752. };
  1753. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  1754. oi.value = scrollValues[i];
  1755. oi.probability = 30;
  1756. possibleObjects.push_back(oi);
  1757. }
  1758. //pandora box with gold
  1759. for (int i = 1; i < 5; i++)
  1760. {
  1761. oi.generateObject = [i]() -> CGObjectInstance *
  1762. {
  1763. auto obj = new CGPandoraBox();
  1764. obj->ID = Obj::PANDORAS_BOX;
  1765. obj->subID = 0;
  1766. obj->resources[Res::GOLD] = i * 5000;
  1767. return obj;
  1768. };
  1769. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1770. oi.value = i * 5000;;
  1771. oi.probability = 5;
  1772. possibleObjects.push_back(oi);
  1773. }
  1774. //pandora box with experience
  1775. for (int i = 1; i < 5; i++)
  1776. {
  1777. oi.generateObject = [i]() -> CGObjectInstance *
  1778. {
  1779. auto obj = new CGPandoraBox();
  1780. obj->ID = Obj::PANDORAS_BOX;
  1781. obj->subID = 0;
  1782. obj->gainedExp = i * 5000;
  1783. return obj;
  1784. };
  1785. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1786. oi.value = i * 6000;;
  1787. oi.probability = 20;
  1788. possibleObjects.push_back(oi);
  1789. }
  1790. //pandora box with creatures
  1791. static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
  1792. auto creatureToCount = [](CCreature * creature) -> int
  1793. {
  1794. int actualTier = creature->level > 7 ? 6 : creature->level - 1;
  1795. float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
  1796. if (creaturesAmount <= 5)
  1797. {
  1798. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1799. if (creaturesAmount < 1)
  1800. return 0;
  1801. }
  1802. else if (creaturesAmount <= 12)
  1803. {
  1804. (creaturesAmount /= 2) *= 2;
  1805. }
  1806. else if (creaturesAmount <= 50)
  1807. {
  1808. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1809. }
  1810. else
  1811. {
  1812. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1813. }
  1814. return creaturesAmount;
  1815. };
  1816. for (auto creature : creatures)
  1817. {
  1818. int creaturesAmount = creatureToCount(creature);
  1819. if (!creaturesAmount)
  1820. continue;
  1821. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1822. {
  1823. auto obj = new CGPandoraBox();
  1824. obj->ID = Obj::PANDORAS_BOX;
  1825. obj->subID = 0;
  1826. auto stack = new CStackInstance(creature, creaturesAmount);
  1827. obj->creatures.putStack(SlotID(0), stack);
  1828. return obj;
  1829. };
  1830. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1831. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
  1832. oi.probability = 3;
  1833. possibleObjects.push_back(oi);
  1834. }
  1835. //Pandora with 12 spells of certain level
  1836. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1837. {
  1838. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1839. {
  1840. auto obj = new CGPandoraBox();
  1841. obj->ID = Obj::PANDORAS_BOX;
  1842. obj->subID = 0;
  1843. std::vector <CSpell *> spells;
  1844. for (auto spell : VLC->spellh->objects)
  1845. {
  1846. if (!spell->isSpecialSpell() && spell->level == i)
  1847. spells.push_back(spell);
  1848. }
  1849. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1850. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1851. {
  1852. obj->spells.push_back(spells[j]->id);
  1853. }
  1854. return obj;
  1855. };
  1856. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1857. oi.value = (i + 1) * 2500; //5000 - 15000
  1858. oi.probability = 2;
  1859. possibleObjects.push_back(oi);
  1860. }
  1861. //Pandora with 15 spells of certain school
  1862. for (int i = 0; i < 4; i++)
  1863. {
  1864. oi.generateObject = [i,gen]() -> CGObjectInstance *
  1865. {
  1866. auto obj = new CGPandoraBox();
  1867. obj->ID = Obj::PANDORAS_BOX;
  1868. obj->subID = 0;
  1869. std::vector <CSpell *> spells;
  1870. for (auto spell : VLC->spellh->objects)
  1871. {
  1872. if (!spell->isSpecialSpell() && spell->school[(ESpellSchool)i])
  1873. spells.push_back(spell);
  1874. }
  1875. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1876. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1877. {
  1878. obj->spells.push_back(spells[j]->id);
  1879. }
  1880. return obj;
  1881. };
  1882. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1883. oi.value = 15000;
  1884. oi.probability = 2;
  1885. possibleObjects.push_back(oi);
  1886. }
  1887. // Pandora box with 60 random spells
  1888. oi.generateObject = [gen]() -> CGObjectInstance *
  1889. {
  1890. auto obj = new CGPandoraBox();
  1891. obj->ID = Obj::PANDORAS_BOX;
  1892. obj->subID = 0;
  1893. std::vector <CSpell *> spells;
  1894. for (auto spell : VLC->spellh->objects)
  1895. {
  1896. if (!spell->isSpecialSpell())
  1897. spells.push_back(spell);
  1898. }
  1899. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1900. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1901. {
  1902. obj->spells.push_back(spells[j]->id);
  1903. }
  1904. return obj;
  1905. };
  1906. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1907. oi.value = 30000;
  1908. oi.probability = 2;
  1909. possibleObjects.push_back(oi);
  1910. //seer huts with creatures or generic rewards
  1911. //if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  1912. if (false) //FIXME: Seer Huts are bugged
  1913. {
  1914. static const int genericSeerHuts = 8;
  1915. int seerHutsPerType = 0;
  1916. const int questArtsRemaining = gen->getQuestArtsRemaning().size();
  1917. //general issue is that not many artifact types are available for quests
  1918. if (questArtsRemaining >= genericSeerHuts + creatures.size())
  1919. {
  1920. seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
  1921. }
  1922. else if (questArtsRemaining >= genericSeerHuts)
  1923. {
  1924. seerHutsPerType = 1;
  1925. }
  1926. oi.maxPerZone = seerHutsPerType;
  1927. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  1928. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  1929. {
  1930. ObjectInfo artInfo;
  1931. artInfo.probability = 1e6; //99,9% to spawn that art in first treasure pile
  1932. artInfo.maxPerZone = 1;
  1933. artInfo.value = 2000; //treasure art
  1934. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  1935. artInfo.generateObject = [id]() -> CGObjectInstance *
  1936. {
  1937. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  1938. return handler->create(handler->getTemplates().front());
  1939. };
  1940. return artInfo;
  1941. };
  1942. for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  1943. {
  1944. auto creature = creatures[i];
  1945. int creaturesAmount = creatureToCount(creature);
  1946. if (!creaturesAmount)
  1947. continue;
  1948. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  1949. oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  1950. {
  1951. auto obj = new CGSeerHut();
  1952. obj->ID = Obj::SEER_HUT;
  1953. obj->subID = randomAppearance;
  1954. obj->rewardType = CGSeerHut::CREATURE;
  1955. obj->rID = creature->idNumber;
  1956. obj->rVal = creaturesAmount;
  1957. obj->quest->missionType = CQuest::MISSION_ART;
  1958. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  1959. obj->quest->m5arts.push_back(artid);
  1960. gen->banQuestArt(artid);
  1961. gen->map->addQuest(obj);
  1962. this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
  1963. return obj;
  1964. };
  1965. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  1966. oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
  1967. oi.probability = 3;
  1968. possibleObjects.push_back(oi);
  1969. }
  1970. static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
  1971. static int seerValues[] = { 2000, 5333, 8666, 12000 };
  1972. for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
  1973. {
  1974. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  1975. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  1976. oi.value = seerValues[i];
  1977. oi.probability = 10;
  1978. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  1979. {
  1980. auto obj = new CGSeerHut();
  1981. obj->ID = Obj::SEER_HUT;
  1982. obj->subID = randomAppearance;
  1983. obj->rewardType = CGSeerHut::EXPERIENCE;
  1984. obj->rID = 0; //unitialized?
  1985. obj->rVal = seerExpGold[i];
  1986. obj->quest->missionType = CQuest::MISSION_ART;
  1987. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  1988. obj->quest->m5arts.push_back(artid);
  1989. gen->banQuestArt(artid);
  1990. gen->map->addQuest(obj);
  1991. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  1992. return obj;
  1993. };
  1994. possibleObjects.push_back(oi);
  1995. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  1996. {
  1997. auto obj = new CGSeerHut();
  1998. obj->ID = Obj::SEER_HUT;
  1999. obj->subID = randomAppearance;
  2000. obj->rewardType = CGSeerHut::RESOURCES;
  2001. obj->rID = Res::GOLD;
  2002. obj->rVal = seerExpGold[i];
  2003. obj->quest->missionType = CQuest::MISSION_ART;
  2004. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2005. obj->quest->m5arts.push_back(artid);
  2006. gen->banQuestArt(artid);
  2007. gen->map->addQuest(obj);
  2008. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2009. return obj;
  2010. };
  2011. possibleObjects.push_back(oi);
  2012. }
  2013. }
  2014. }
  2015. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2016. {
  2017. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  2018. }