CRmgTemplateZone.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397
  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. //tighten obstacles to improve visuals
  1162. for (int i = 0; i < 3; ++i)
  1163. {
  1164. int blockedTiles = 0;
  1165. int freeTiles = 0;
  1166. for (auto tile : tileinfo)
  1167. {
  1168. if (!gen->isPossible(tile)) //only possible tiles can change
  1169. continue;
  1170. int blockedNeighbours = 0;
  1171. int freeNeighbours = 0;
  1172. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1173. {
  1174. if (gen->isBlocked(pos))
  1175. blockedNeighbours++;
  1176. if (gen->isFree(pos))
  1177. freeNeighbours++;
  1178. });
  1179. if (blockedNeighbours > 4)
  1180. {
  1181. gen->setOccupied(tile, ETileType::BLOCKED);
  1182. blockedTiles++;
  1183. }
  1184. else if (freeNeighbours > 4)
  1185. {
  1186. gen->setOccupied(tile, ETileType::FREE);
  1187. freeTiles++;
  1188. }
  1189. }
  1190. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1191. }
  1192. #define MAKE_COOL_UNDERGROUND_TUNNELS false
  1193. if (pos.z && MAKE_COOL_UNDERGROUND_TUNNELS) //underground
  1194. {
  1195. std::vector<int3> rockTiles;
  1196. for (auto tile : tileinfo)
  1197. {
  1198. if (gen->shouldBeBlocked(tile))
  1199. {
  1200. bool placeRock = true;
  1201. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1202. {
  1203. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1204. placeRock = false;
  1205. });
  1206. if (placeRock)
  1207. {
  1208. rockTiles.push_back(tile);
  1209. }
  1210. }
  1211. }
  1212. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1213. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1214. for (auto tile : rockTiles)
  1215. {
  1216. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1217. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1218. //{
  1219. // if (!gen->isUsed(pos))
  1220. // gen->setOccupied (pos, ETileType::BLOCKED);
  1221. //});
  1222. }
  1223. }
  1224. typedef std::vector<ObjectTemplate> obstacleVector;
  1225. //obstacleVector possibleObstacles;
  1226. std::map <ui8, obstacleVector> obstaclesBySize;
  1227. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1228. std::vector<obstaclePair> possibleObstacles;
  1229. //get all possible obstacles for this terrain
  1230. for (auto primaryID : VLC->objtypeh->knownObjects())
  1231. {
  1232. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1233. {
  1234. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1235. if (handler->isStaticObject())
  1236. {
  1237. for (auto temp : handler->getTemplates())
  1238. {
  1239. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1240. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. for (auto o : obstaclesBySize)
  1246. {
  1247. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1248. }
  1249. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1250. {
  1251. return p1.first > p2.first; //bigger obstacles first
  1252. });
  1253. auto sel = gen->editManager->getTerrainSelection();
  1254. sel.clearSelection();
  1255. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1256. {
  1257. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1258. int3 obstaclePos = tile + temp.getBlockMapOffset();
  1259. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1260. {
  1261. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1262. placeObject(gen, obj, obstaclePos, false);
  1263. return true;
  1264. }
  1265. return false;
  1266. };
  1267. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1268. for (auto tile : boost::adaptors::reverse(tileinfo))
  1269. {
  1270. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1271. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1272. {
  1273. //start from biggets obstacles
  1274. for (int i = 0; i < possibleObstacles.size(); i++)
  1275. {
  1276. if (tryToPlaceObstacleHere(tile, i))
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1283. {
  1284. initTerrainType(gen);
  1285. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1286. addAllPossibleObjects (gen);
  1287. placeMines(gen);
  1288. createRequiredObjects(gen);
  1289. fractalize(gen); //after required objects are created and linked with their own paths
  1290. createTreasures(gen);
  1291. createObstacles(gen);
  1292. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1293. return true;
  1294. }
  1295. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1296. {
  1297. float best_distance = 0;
  1298. bool result = false;
  1299. bool needsGuard = value > minGuardedValue;
  1300. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1301. for(auto tile : possibleTiles)
  1302. {
  1303. auto dist = gen->getNearestObjectDistance(tile);
  1304. if ((dist >= min_dist) && (dist > best_distance))
  1305. {
  1306. bool allTilesAvailable = true;
  1307. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1308. {
  1309. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1310. {
  1311. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1312. }
  1313. });
  1314. if (allTilesAvailable)
  1315. {
  1316. best_distance = dist;
  1317. pos = tile;
  1318. result = true;
  1319. }
  1320. }
  1321. }
  1322. if (result)
  1323. {
  1324. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1325. }
  1326. return result;
  1327. }
  1328. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1329. {
  1330. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1331. return false;
  1332. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1333. for (auto blockingTile : tilesBlockedByObject)
  1334. {
  1335. int3 t = pos + blockingTile;
  1336. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1337. {
  1338. return false; //if at least one tile is not possible, object can't be placed here
  1339. }
  1340. }
  1341. return true;
  1342. }
  1343. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1344. {
  1345. bool accessible = false;
  1346. for (int x = -1; x < 2; x++)
  1347. {
  1348. for (int y = -1; y <2; y++)
  1349. {
  1350. if (x && y) //check only if object is visitable from another tile
  1351. {
  1352. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1353. if (!vstd::contains(tilesBlockedByObject, offset))
  1354. {
  1355. int3 nearbyPos = tile + offset;
  1356. if (gen->map->isInTheMap(nearbyPos))
  1357. {
  1358. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1359. accessible = true;
  1360. }
  1361. }
  1362. }
  1363. };
  1364. }
  1365. return accessible;
  1366. }
  1367. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1368. {
  1369. if (obj->appearance.id == Obj::NO_OBJ)
  1370. {
  1371. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1372. if (templates.empty())
  1373. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1374. obj->appearance = templates.front();
  1375. }
  1376. }
  1377. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1378. {
  1379. for (auto blockingTile : tilesBlockedByObject)
  1380. {
  1381. int3 t = tile + blockingTile;
  1382. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1383. {
  1384. //if at least one tile is not possible, object can't be placed here
  1385. return false;
  1386. }
  1387. }
  1388. return true;
  1389. }
  1390. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1391. {
  1392. //we need object apperance to deduce free tile
  1393. setTemplateForObject(gen, obj);
  1394. //si32 min_dist = sqrt(tileinfo.size()/density);
  1395. int best_distance = 0;
  1396. bool result = false;
  1397. //si32 w = gen->map->width;
  1398. //si32 h = gen->map->height;
  1399. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1400. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1401. for (auto tile : tileinfo)
  1402. {
  1403. //object must be accessible from at least one surounding tile
  1404. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1405. continue;
  1406. auto ti = gen->getTile(tile);
  1407. auto dist = ti.getNearestObjectDistance();
  1408. //avoid borders
  1409. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1410. {
  1411. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1412. {
  1413. best_distance = dist;
  1414. pos = tile;
  1415. result = true;
  1416. }
  1417. }
  1418. }
  1419. if (result)
  1420. {
  1421. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1422. }
  1423. return result;
  1424. }
  1425. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1426. {
  1427. if (!gen->map->isInTheMap(pos))
  1428. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1429. object->pos = pos;
  1430. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1431. 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()));
  1432. for (auto tile : object->getBlockedPos())
  1433. {
  1434. if (!gen->map->isInTheMap(tile))
  1435. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1436. }
  1437. if (object->appearance.id == Obj::NO_OBJ)
  1438. {
  1439. auto terrainType = gen->map->getTile(pos).terType;
  1440. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1441. if (templates.empty())
  1442. 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));
  1443. object->appearance = templates.front();
  1444. }
  1445. gen->editManager->insertObject(object, pos);
  1446. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1447. }
  1448. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1449. {
  1450. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1451. checkAndPlaceObject (gen, object, pos);
  1452. auto points = object->getBlockedPos();
  1453. if (object->isVisitable())
  1454. points.insert(pos + object->getVisitableOffset());
  1455. points.insert(pos);
  1456. for(auto p : points)
  1457. {
  1458. if (gen->map->isInTheMap(p))
  1459. {
  1460. gen->setOccupied(p, ETileType::USED);
  1461. }
  1462. }
  1463. if (updateDistance)
  1464. {
  1465. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1466. {
  1467. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1468. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1469. }
  1470. }
  1471. if (object->ID == Obj::SEER_HUT) //debug
  1472. {
  1473. CGSeerHut * sh = dynamic_cast<CGSeerHut *>(object);
  1474. auto artid = sh->quest->m5arts.front();
  1475. logGlobal->warnStream() << boost::format("Placed Seer Hut at %s, quest artifact %d is %s") % object->pos % artid % VLC->arth->artifacts[artid]->Name();
  1476. }
  1477. }
  1478. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1479. {
  1480. placeObject(gen, object, pos);
  1481. guardObject(gen, object, str, zoneGuard);
  1482. }
  1483. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1484. {
  1485. //get all tiles from which this object can be accessed
  1486. int3 visitable = object->visitablePos();
  1487. std::vector<int3> tiles;
  1488. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1489. gen->foreach_neighbour(visitable, [&](int3& pos)
  1490. {
  1491. if (gen->isPossible(pos))
  1492. {
  1493. if (!vstd::contains(tilesBlockedByObject, pos))
  1494. {
  1495. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1496. {
  1497. tiles.push_back(pos);
  1498. }
  1499. }
  1500. };
  1501. });
  1502. return tiles;
  1503. }
  1504. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1505. {
  1506. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1507. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1508. int3 guardTile(-1,-1,-1);
  1509. for (auto tile : tiles)
  1510. {
  1511. //crunching path may fail if center of the zone is directly over wide object
  1512. //make sure object is accessible before surrounding it with blocked tiles
  1513. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1514. {
  1515. guardTile = tile;
  1516. break;
  1517. }
  1518. }
  1519. if (!guardTile.valid())
  1520. {
  1521. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1522. return false;
  1523. }
  1524. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1525. {
  1526. for (auto pos : tiles)
  1527. {
  1528. if (!gen->isFree(pos))
  1529. gen->setOccupied(pos, ETileType::BLOCKED);
  1530. }
  1531. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1532. {
  1533. if (gen->isPossible(pos))
  1534. gen->setOccupied (pos, ETileType::FREE);
  1535. });
  1536. gen->setOccupied (guardTile, ETileType::USED);
  1537. }
  1538. else //allow no guard or other object in front of this object
  1539. {
  1540. for (auto tile : tiles)
  1541. if (gen->isPossible(tile))
  1542. gen->setOccupied (tile, ETileType::FREE);
  1543. }
  1544. return true;
  1545. }
  1546. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1547. {
  1548. //int objectsVisitableFromBottom = 0; //for debug
  1549. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1550. ui32 total = 0;
  1551. //calculate actual treasure value range based on remaining value
  1552. ui32 maxVal = desiredValue - currentValue;
  1553. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1554. //roulette wheel
  1555. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1556. {
  1557. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1558. {
  1559. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1560. int3 newVisitablePos = info.nextTreasurePos;
  1561. if (!oi.templ.isVisitableFromTop())
  1562. {
  1563. //objectsVisitableFromBottom++;
  1564. //there must be free tiles under object
  1565. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1566. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1567. continue;
  1568. }
  1569. //NOTE: y coordinate grows downwards
  1570. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1571. {
  1572. bool fitsHere = false;
  1573. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1574. {
  1575. for (auto tile : info.visitableFromTopPositions)
  1576. {
  1577. int3 actualTile = tile + newVisitableOffset;
  1578. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1579. {
  1580. fitsHere = true;
  1581. break;
  1582. }
  1583. }
  1584. for (auto tile : info.visitableFromBottomPositions)
  1585. {
  1586. int3 actualTile = tile + newVisitableOffset;
  1587. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1588. {
  1589. fitsHere = true;
  1590. break;
  1591. }
  1592. }
  1593. }
  1594. else //if new object is not visitable from top, it must be accessible from below or side
  1595. {
  1596. for (auto tile : info.visitableFromTopPositions)
  1597. {
  1598. int3 actualTile = tile + newVisitableOffset;
  1599. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1600. {
  1601. fitsHere = true;
  1602. break;
  1603. }
  1604. }
  1605. for (auto tile : info.visitableFromBottomPositions)
  1606. {
  1607. int3 actualTile = tile + newVisitableOffset;
  1608. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1609. {
  1610. fitsHere = true;
  1611. break;
  1612. }
  1613. }
  1614. }
  1615. if (!fitsHere)
  1616. continue;
  1617. }
  1618. //now check blockmap, including our already reserved pile area
  1619. bool fitsBlockmap = true;
  1620. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1621. blockedOffsets.insert (newVisitableOffset);
  1622. for (auto blockingTile : blockedOffsets)
  1623. {
  1624. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1625. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1626. {
  1627. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1628. break;
  1629. }
  1630. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1631. {
  1632. fitsBlockmap = false;
  1633. break;
  1634. }
  1635. }
  1636. if (!fitsBlockmap)
  1637. continue;
  1638. total += oi.probability;
  1639. //assert (oi.value > 0);
  1640. tresholds.push_back (std::make_pair (total, oi));
  1641. }
  1642. }
  1643. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1644. if (tresholds.empty())
  1645. {
  1646. ObjectInfo oi;
  1647. //Generate pandora Box with gold if the value is extremely high
  1648. if (minValue > 20000) //we don't have object valuable enough
  1649. {
  1650. oi.generateObject = [minValue]() -> CGObjectInstance *
  1651. {
  1652. auto obj = new CGPandoraBox();
  1653. obj->ID = Obj::PANDORAS_BOX;
  1654. obj->subID = 0;
  1655. obj->resources[Res::GOLD] = minValue;
  1656. return obj;
  1657. };
  1658. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1659. oi.value = minValue;
  1660. oi.probability = 0;
  1661. }
  1662. else //generate empty object with 0 value if the value if we can't spawn anything
  1663. {
  1664. oi.generateObject = [gen]() -> CGObjectInstance *
  1665. {
  1666. return nullptr;
  1667. };
  1668. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1669. oi.value = 0; // this field is checked to determine no object
  1670. oi.probability = 0;
  1671. }
  1672. return oi;
  1673. }
  1674. else
  1675. {
  1676. int r = gen->rand.nextInt (1, total);
  1677. for (auto t : tresholds)
  1678. {
  1679. if (r <= t.first)
  1680. return t.second;
  1681. }
  1682. assert (0); //we should never be here
  1683. }
  1684. //FIXME: control reaches end of non-void function. Missing return?
  1685. }
  1686. void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
  1687. {
  1688. ObjectInfo oi;
  1689. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1690. int numZones = gen->getZones().size();
  1691. std::vector<CCreature *> creatures; //native creatures for this zone
  1692. for (auto cre : VLC->creh->creatures)
  1693. {
  1694. if (!cre->special && cre->faction == townType)
  1695. {
  1696. creatures.push_back(cre);
  1697. }
  1698. }
  1699. for (auto primaryID : VLC->objtypeh->knownObjects())
  1700. {
  1701. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1702. {
  1703. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1704. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1705. {
  1706. for (auto temp : handler->getTemplates())
  1707. {
  1708. if (temp.canBePlacedAt(terrainType))
  1709. {
  1710. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1711. {
  1712. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1713. };
  1714. auto rmgInfo = handler->getRMGInfo();
  1715. oi.value = rmgInfo.value;
  1716. oi.probability = rmgInfo.rarity;
  1717. oi.templ = temp;
  1718. oi.maxPerZone = rmgInfo.zoneLimit;
  1719. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1720. possibleObjects.push_back(oi);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. }
  1726. //prisons
  1727. //levels 1, 5, 10, 20, 30
  1728. static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
  1729. static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
  1730. for (int i = 0; i < 5; i++)
  1731. {
  1732. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1733. {
  1734. auto obj = new CGHeroInstance;
  1735. obj->ID = Obj::PRISON;
  1736. std::vector<ui32> possibleHeroes;
  1737. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1738. {
  1739. if (gen->map->allowedHeroes[j])
  1740. possibleHeroes.push_back(j);
  1741. }
  1742. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1743. obj->subID = hid; //will be initialized later
  1744. obj->exp = prisonExp[i];
  1745. obj->setOwner(PlayerColor::NEUTRAL);
  1746. gen->map->allowedHeroes[hid] = false; //ban this hero
  1747. gen->decreasePrisonsRemaining();
  1748. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1749. return obj;
  1750. };
  1751. oi.setTemplate(Obj::PRISON, 0, terrainType);
  1752. oi.value = prisonValues[i];
  1753. oi.probability = 30;
  1754. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1755. possibleObjects.push_back(oi);
  1756. }
  1757. //all following objects are unlimited
  1758. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1759. //dwellings
  1760. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1761. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1762. static int elementalConfluxROE[] = { 7, 13, 16, 47 };
  1763. for (int i = 0; i < 4; i++)
  1764. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1765. for (auto secondaryID : subObjects)
  1766. {
  1767. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1768. auto creatures = dwellingHandler->getProducedCreatures();
  1769. if (creatures.empty())
  1770. continue;
  1771. auto cre = creatures.front();
  1772. if (cre->faction == townType)
  1773. {
  1774. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1775. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1776. oi.probability = 40;
  1777. for (auto temp : dwellingHandler->getTemplates())
  1778. {
  1779. if (temp.canBePlacedAt(terrainType))
  1780. {
  1781. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1782. {
  1783. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1784. //dwellingHandler->configureObject(obj, gen->rand);
  1785. obj->tempOwner = PlayerColor::NEUTRAL;
  1786. return obj;
  1787. };
  1788. oi.templ = temp;
  1789. possibleObjects.push_back(oi);
  1790. }
  1791. }
  1792. }
  1793. }
  1794. static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
  1795. for (int i = 0; i < 5; i++)
  1796. {
  1797. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1798. {
  1799. auto obj = new CGArtifact();
  1800. obj->ID = Obj::SPELL_SCROLL;
  1801. obj->subID = 0;
  1802. std::vector<SpellID> out;
  1803. //TODO: unify with cb->getAllowedSpells?
  1804. for (ui32 spellid = 0; spellid < gen->map->allowedSpell.size(); spellid++) //spellh size appears to be greater (?)
  1805. {
  1806. const CSpell *spell = SpellID(spellid).toSpell();
  1807. if (gen->map->allowedSpell[spell->id] && spell->level == i + 1)
  1808. {
  1809. out.push_back(spell->id);
  1810. }
  1811. }
  1812. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1813. gen->map->addNewArtifactInstance(a);
  1814. obj->storedArtifact = a;
  1815. return obj;
  1816. };
  1817. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  1818. oi.value = scrollValues[i];
  1819. oi.probability = 30;
  1820. possibleObjects.push_back(oi);
  1821. }
  1822. //pandora box with gold
  1823. for (int i = 1; i < 5; i++)
  1824. {
  1825. oi.generateObject = [i]() -> CGObjectInstance *
  1826. {
  1827. auto obj = new CGPandoraBox();
  1828. obj->ID = Obj::PANDORAS_BOX;
  1829. obj->subID = 0;
  1830. obj->resources[Res::GOLD] = i * 5000;
  1831. return obj;
  1832. };
  1833. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1834. oi.value = i * 5000;;
  1835. oi.probability = 5;
  1836. possibleObjects.push_back(oi);
  1837. }
  1838. //pandora box with experience
  1839. for (int i = 1; i < 5; i++)
  1840. {
  1841. oi.generateObject = [i]() -> CGObjectInstance *
  1842. {
  1843. auto obj = new CGPandoraBox();
  1844. obj->ID = Obj::PANDORAS_BOX;
  1845. obj->subID = 0;
  1846. obj->gainedExp = i * 5000;
  1847. return obj;
  1848. };
  1849. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1850. oi.value = i * 6000;;
  1851. oi.probability = 20;
  1852. possibleObjects.push_back(oi);
  1853. }
  1854. //pandora box with creatures
  1855. static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
  1856. auto creatureToCount = [](CCreature * creature) -> int
  1857. {
  1858. int actualTier = creature->level > 7 ? 6 : creature->level - 1;
  1859. float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
  1860. if (creaturesAmount <= 5)
  1861. {
  1862. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1863. if (creaturesAmount < 1)
  1864. return 0;
  1865. }
  1866. else if (creaturesAmount <= 12)
  1867. {
  1868. (creaturesAmount /= 2) *= 2;
  1869. }
  1870. else if (creaturesAmount <= 50)
  1871. {
  1872. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1873. }
  1874. else
  1875. {
  1876. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1877. }
  1878. return creaturesAmount;
  1879. };
  1880. for (auto creature : creatures)
  1881. {
  1882. int creaturesAmount = creatureToCount(creature);
  1883. if (!creaturesAmount)
  1884. continue;
  1885. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1886. {
  1887. auto obj = new CGPandoraBox();
  1888. obj->ID = Obj::PANDORAS_BOX;
  1889. obj->subID = 0;
  1890. auto stack = new CStackInstance(creature, creaturesAmount);
  1891. obj->creatures.putStack(SlotID(0), stack);
  1892. return obj;
  1893. };
  1894. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1895. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
  1896. oi.probability = 3;
  1897. possibleObjects.push_back(oi);
  1898. }
  1899. //Pandora with 12 spells of certain level
  1900. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1901. {
  1902. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1903. {
  1904. auto obj = new CGPandoraBox();
  1905. obj->ID = Obj::PANDORAS_BOX;
  1906. obj->subID = 0;
  1907. std::vector <CSpell *> spells;
  1908. for (auto spell : VLC->spellh->objects)
  1909. {
  1910. if (!spell->isSpecialSpell() && spell->level == i)
  1911. spells.push_back(spell);
  1912. }
  1913. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1914. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1915. {
  1916. obj->spells.push_back(spells[j]->id);
  1917. }
  1918. return obj;
  1919. };
  1920. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1921. oi.value = (i + 1) * 2500; //5000 - 15000
  1922. oi.probability = 2;
  1923. possibleObjects.push_back(oi);
  1924. }
  1925. //Pandora with 15 spells of certain school
  1926. for (int i = 0; i < 4; i++)
  1927. {
  1928. oi.generateObject = [i,gen]() -> CGObjectInstance *
  1929. {
  1930. auto obj = new CGPandoraBox();
  1931. obj->ID = Obj::PANDORAS_BOX;
  1932. obj->subID = 0;
  1933. std::vector <CSpell *> spells;
  1934. for (auto spell : VLC->spellh->objects)
  1935. {
  1936. if (!spell->isSpecialSpell() && spell->school[(ESpellSchool)i])
  1937. spells.push_back(spell);
  1938. }
  1939. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1940. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1941. {
  1942. obj->spells.push_back(spells[j]->id);
  1943. }
  1944. return obj;
  1945. };
  1946. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1947. oi.value = 15000;
  1948. oi.probability = 2;
  1949. possibleObjects.push_back(oi);
  1950. }
  1951. // Pandora box with 60 random spells
  1952. oi.generateObject = [gen]() -> CGObjectInstance *
  1953. {
  1954. auto obj = new CGPandoraBox();
  1955. obj->ID = Obj::PANDORAS_BOX;
  1956. obj->subID = 0;
  1957. std::vector <CSpell *> spells;
  1958. for (auto spell : VLC->spellh->objects)
  1959. {
  1960. if (!spell->isSpecialSpell())
  1961. spells.push_back(spell);
  1962. }
  1963. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1964. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1965. {
  1966. obj->spells.push_back(spells[j]->id);
  1967. }
  1968. return obj;
  1969. };
  1970. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1971. oi.value = 30000;
  1972. oi.probability = 2;
  1973. possibleObjects.push_back(oi);
  1974. //seer huts with creatures or generic rewards
  1975. if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  1976. {
  1977. static const int genericSeerHuts = 8;
  1978. int seerHutsPerType = 0;
  1979. const int questArtsRemaining = gen->getQuestArtsRemaning().size();
  1980. //general issue is that not many artifact types are available for quests
  1981. if (questArtsRemaining >= genericSeerHuts + creatures.size())
  1982. {
  1983. seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
  1984. }
  1985. else if (questArtsRemaining >= genericSeerHuts)
  1986. {
  1987. seerHutsPerType = 1;
  1988. }
  1989. oi.maxPerZone = seerHutsPerType;
  1990. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  1991. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  1992. {
  1993. ObjectInfo artInfo;
  1994. artInfo.probability = 1e6; //99,9% to spawn that art in first treasure pile
  1995. artInfo.maxPerZone = 1;
  1996. artInfo.value = 2000; //treasure art
  1997. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  1998. artInfo.generateObject = [id]() -> CGObjectInstance *
  1999. {
  2000. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  2001. return handler->create(handler->getTemplates().front());
  2002. };
  2003. return artInfo;
  2004. };
  2005. for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  2006. {
  2007. auto creature = creatures[i];
  2008. int creaturesAmount = creatureToCount(creature);
  2009. if (!creaturesAmount)
  2010. continue;
  2011. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2012. oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2013. {
  2014. auto obj = new CGSeerHut();
  2015. obj->ID = Obj::SEER_HUT;
  2016. obj->subID = randomAppearance;
  2017. obj->rewardType = CGSeerHut::CREATURE;
  2018. obj->rID = creature->idNumber;
  2019. obj->rVal = creaturesAmount;
  2020. obj->quest->missionType = CQuest::MISSION_ART;
  2021. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2022. obj->quest->m5arts.push_back(artid);
  2023. gen->banQuestArt(artid);
  2024. gen->map->addQuest(obj);
  2025. this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
  2026. return obj;
  2027. };
  2028. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2029. oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
  2030. oi.probability = 3;
  2031. possibleObjects.push_back(oi);
  2032. }
  2033. static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
  2034. static int seerValues[] = { 2000, 5333, 8666, 12000 };
  2035. for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
  2036. {
  2037. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2038. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2039. oi.value = seerValues[i];
  2040. oi.probability = 10;
  2041. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2042. {
  2043. auto obj = new CGSeerHut();
  2044. obj->ID = Obj::SEER_HUT;
  2045. obj->subID = randomAppearance;
  2046. obj->rewardType = CGSeerHut::EXPERIENCE;
  2047. obj->rID = 0; //unitialized?
  2048. obj->rVal = seerExpGold[i];
  2049. obj->quest->missionType = CQuest::MISSION_ART;
  2050. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2051. obj->quest->m5arts.push_back(artid);
  2052. gen->banQuestArt(artid);
  2053. gen->map->addQuest(obj);
  2054. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2055. return obj;
  2056. };
  2057. possibleObjects.push_back(oi);
  2058. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2059. {
  2060. auto obj = new CGSeerHut();
  2061. obj->ID = Obj::SEER_HUT;
  2062. obj->subID = randomAppearance;
  2063. obj->rewardType = CGSeerHut::RESOURCES;
  2064. obj->rID = Res::GOLD;
  2065. obj->rVal = seerExpGold[i];
  2066. obj->quest->missionType = CQuest::MISSION_ART;
  2067. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2068. obj->quest->m5arts.push_back(artid);
  2069. gen->banQuestArt(artid);
  2070. gen->map->addQuest(obj);
  2071. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2072. return obj;
  2073. };
  2074. possibleObjects.push_back(oi);
  2075. }
  2076. }
  2077. }
  2078. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2079. {
  2080. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  2081. }