CRmgTemplateZone.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  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 "../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. //TODO
  695. //update treasure pile area
  696. int3 visitablePos = info.nextTreasurePos;
  697. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  698. if (oi.templ.isVisitableFromTop())
  699. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  700. else
  701. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  702. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  703. {
  704. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  705. info.occupiedPositions.insert(blockPos);
  706. info.blockedPositions.insert(blockPos);
  707. }
  708. info.occupiedPositions.insert(visitablePos);
  709. currentValue += oi.value;
  710. treasures[info.nextTreasurePos] = object;
  711. //now find place for next object
  712. int3 placeFound(-1,-1,-1);
  713. //randomize next position from among possible ones
  714. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  715. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  716. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  717. {
  718. return lhs.y < rhs.y;
  719. };
  720. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  721. for (auto tile : boundaryCopy)
  722. {
  723. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  724. {
  725. bool here = true;
  726. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  727. {
  728. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  729. here = false;
  730. });
  731. if (here)
  732. {
  733. placeFound = tile;
  734. break;
  735. }
  736. }
  737. }
  738. if (placeFound.valid())
  739. info.nextTreasurePos = placeFound;
  740. else
  741. break; //no more place to add any objects
  742. }
  743. }
  744. if (treasures.size())
  745. {
  746. //find object closest to zone center, then connect it to the middle of the zone
  747. int3 closestFreeTile (-1,-1,-1);
  748. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  749. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  750. else
  751. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  752. int3 closestTile = int3(-1,-1,-1);
  753. float minDistance = 1e10;
  754. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  755. {
  756. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  757. {
  758. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  759. minDistance = closestFreeTile.dist2d(visitablePos);
  760. }
  761. }
  762. if (!closestTile.valid())
  763. {
  764. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  765. {
  766. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  767. {
  768. closestTile = visitablePos;
  769. minDistance = closestFreeTile.dist2d(visitablePos);
  770. }
  771. }
  772. }
  773. assert (closestTile.valid());
  774. for (auto tile : info.occupiedPositions)
  775. {
  776. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  777. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  778. }
  779. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  780. {
  781. //we can't connect this pile, just block it off and start over
  782. for (auto treasure : treasures)
  783. {
  784. if (gen->isPossible(treasure.first))
  785. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  786. }
  787. return true;
  788. }
  789. //update boundary around our objects, including knowledge about objects visitable from bottom
  790. boundary.clear();
  791. for (auto tile : info.visitableFromBottomPositions)
  792. {
  793. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  794. {
  795. if (pos.y >= tile.y) //don't block these objects from above
  796. boundary.insert(pos);
  797. });
  798. }
  799. for (auto tile : info.visitableFromTopPositions)
  800. {
  801. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  802. {
  803. boundary.insert(pos);
  804. });
  805. }
  806. bool isPileGuarded = currentValue >= minGuardedValue;
  807. for (auto tile : boundary) //guard must be standing there
  808. {
  809. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  810. {
  811. guardPos = tile;
  812. break;
  813. }
  814. }
  815. if (guardPos.valid())
  816. {
  817. for (auto treasure : treasures)
  818. {
  819. int3 visitableOffset = treasure.second->getVisitableOffset();
  820. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  821. }
  822. if (addMonster(gen, guardPos, currentValue, false))
  823. {//block only if the object is guarded
  824. for (auto tile : boundary)
  825. {
  826. if (gen->isPossible(tile))
  827. gen->setOccupied(tile, ETileType::BLOCKED);
  828. }
  829. //do not spawn anything near monster
  830. gen->foreach_neighbour(guardPos, [gen](int3 pos)
  831. {
  832. if (gen->isPossible(pos))
  833. gen->setOccupied(pos, ETileType::FREE);
  834. });
  835. }
  836. else //mo monster in this pile, make some free space (needed?)
  837. {
  838. for (auto tile : boundary)
  839. if (gen->isPossible(tile))
  840. gen->setOccupied(tile, ETileType::FREE);
  841. }
  842. }
  843. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  844. {
  845. for (auto treasure : treasures)
  846. {
  847. if (gen->isPossible(treasure.first))
  848. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  849. delete treasure.second;
  850. }
  851. }
  852. return true;
  853. }
  854. else //we did not place eveyrthing successfully
  855. return false;
  856. }
  857. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  858. {
  859. //FIXME: handle case that this player is not present -> towns should be set to neutral
  860. int totalTowns = 0;
  861. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  862. {
  863. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  864. for (auto tile : town->getBlockedPos())
  865. {
  866. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  867. {
  868. if (gen->isPossible(pos))
  869. {
  870. gen->setOccupied(pos, ETileType::FREE);
  871. }
  872. });
  873. }
  874. };
  875. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  876. {
  877. for (int i = 0; i < count; i++)
  878. {
  879. auto town = new CGTownInstance();
  880. town->ID = Obj::TOWN;
  881. if (this->townsAreSameType)
  882. town->subID = townType;
  883. else
  884. {
  885. if (townTypes.size())
  886. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  887. else
  888. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  889. }
  890. town->tempOwner = player;
  891. if (hasFort)
  892. town->builtBuildings.insert(BuildingID::FORT);
  893. town->builtBuildings.insert(BuildingID::DEFAULT);
  894. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  895. {
  896. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  897. town->possibleSpells.push_back(spell->id);
  898. }
  899. if (!totalTowns)
  900. {
  901. //first town in zone sets the facton of entire zone
  902. town->subID = townType;
  903. //register MAIN town of zone
  904. gen->registerZone(town->subID);
  905. //first town in zone goes in the middle
  906. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  907. cutPathAroundTown(town);
  908. }
  909. else
  910. addRequiredObject (town);
  911. totalTowns++;
  912. }
  913. };
  914. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  915. {
  916. //set zone types to player faction, generate main town
  917. logGlobal->infoStream() << "Preparing playing zone";
  918. int player_id = *owner - 1;
  919. auto & playerInfo = gen->map->players[player_id];
  920. if (playerInfo.canAnyonePlay())
  921. {
  922. PlayerColor player(player_id);
  923. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  924. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  925. {
  926. if (townTypes.size())
  927. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  928. else
  929. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  930. }
  931. auto town = new CGTownInstance();
  932. town->ID = Obj::TOWN;
  933. town->subID = townType;
  934. town->tempOwner = player;
  935. town->builtBuildings.insert(BuildingID::FORT);
  936. town->builtBuildings.insert(BuildingID::DEFAULT);
  937. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  938. {
  939. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  940. town->possibleSpells.push_back(spell->id);
  941. }
  942. //towns are big objects and should be centered around visitable position
  943. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  944. cutPathAroundTown(town);
  945. totalTowns++;
  946. //register MAIN town of zone only
  947. gen->registerZone (town->subID);
  948. logGlobal->traceStream() << "Fill player info " << player_id;
  949. // Update player info
  950. playerInfo.allowedFactions.clear();
  951. playerInfo.allowedFactions.insert (townType);
  952. playerInfo.hasMainTown = true;
  953. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  954. playerInfo.generateHeroAtMainTown = true;
  955. //now create actual towns
  956. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  957. addNewTowns (playerTowns.getTownCount(), false, player);
  958. //requiredObjects.push_back(town);
  959. }
  960. else
  961. {
  962. type = ETemplateZoneType::TREASURE;
  963. if (townTypes.size())
  964. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  965. else
  966. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  967. }
  968. }
  969. else //no player
  970. {
  971. if (townTypes.size())
  972. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  973. else
  974. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  975. }
  976. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  977. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  978. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  979. {
  980. //25% chance for neutral
  981. if (gen->rand.nextInt(1, 100) <= 25)
  982. {
  983. townType = ETownType::NEUTRAL;
  984. }
  985. else
  986. {
  987. if (townTypes.size())
  988. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  989. else if (monsterTypes.size())
  990. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  991. }
  992. }
  993. }
  994. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  995. {
  996. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  997. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  998. else
  999. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  1000. //TODO: allow new types of terrain?
  1001. if (pos.z)
  1002. {
  1003. if (terrainType != ETerrainType::LAVA)
  1004. terrainType = ETerrainType::SUBTERRANEAN;
  1005. }
  1006. else
  1007. {
  1008. if (terrainType == ETerrainType::SUBTERRANEAN)
  1009. terrainType = ETerrainType::DIRT;
  1010. }
  1011. paintZoneTerrain (gen, terrainType);
  1012. }
  1013. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  1014. {
  1015. std::vector<int3> tiles;
  1016. for (auto tile : tileinfo)
  1017. {
  1018. tiles.push_back (tile);
  1019. }
  1020. gen->editManager->getTerrainSelection().setSelection(tiles);
  1021. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1022. }
  1023. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  1024. {
  1025. std::vector<Res::ERes> required_mines;
  1026. required_mines.push_back(Res::ERes::WOOD);
  1027. required_mines.push_back(Res::ERes::ORE);
  1028. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1029. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1030. for (const auto & res : woodOre)
  1031. {
  1032. for (int i = 0; i < mines[res]; i++)
  1033. {
  1034. auto mine = new CGMine();
  1035. mine->ID = Obj::MINE;
  1036. mine->subID = static_cast<si32>(res);
  1037. mine->producedResource = res;
  1038. mine->producedQuantity = mine->defaultResProduction();
  1039. addCloseObject(mine, 1500);
  1040. }
  1041. }
  1042. for (const auto & res : preciousResources)
  1043. {
  1044. for (int i = 0; i < mines[res]; i++)
  1045. {
  1046. auto mine = new CGMine();
  1047. mine->ID = Obj::MINE;
  1048. mine->subID = static_cast<si32>(res);
  1049. mine->producedResource = res;
  1050. mine->producedQuantity = mine->defaultResProduction();
  1051. addRequiredObject(mine, 3500);
  1052. }
  1053. }
  1054. for (int i = 0; i < mines[Res::GOLD]; i++)
  1055. {
  1056. auto mine = new CGMine();
  1057. mine->ID = Obj::MINE;
  1058. mine->subID = static_cast<si32>(Res::GOLD);
  1059. mine->producedResource = Res::GOLD;
  1060. mine->producedQuantity = mine->defaultResProduction();
  1061. addRequiredObject(mine, 7000);
  1062. }
  1063. return true;
  1064. }
  1065. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1066. {
  1067. logGlobal->traceStream() << "Creating required objects";
  1068. for(const auto &obj : requiredObjects)
  1069. {
  1070. int3 pos;
  1071. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  1072. {
  1073. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  1074. //TODO CLEANUP!
  1075. return false;
  1076. }
  1077. placeObject (gen, obj.first, pos);
  1078. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1079. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1080. }
  1081. for (const auto &obj : closeObjects)
  1082. {
  1083. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1084. // smallest distance to zone center, greatest distance to nearest object
  1085. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1086. {
  1087. return (this->pos.dist2dSQ(lhs) * 0.5f - gen->getNearestObjectDistance(lhs)) < (this->pos.dist2dSQ(rhs) * 0.5f - gen->getNearestObjectDistance(rhs));
  1088. };
  1089. boost::sort (tiles, isCloser);
  1090. setTemplateForObject(gen, obj.first);
  1091. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1092. bool result = false;
  1093. for (auto tile : tiles)
  1094. {
  1095. //object must be accessible from at least one surounding tile
  1096. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile, tilesBlockedByObject))
  1097. continue;
  1098. //avoid borders
  1099. if (gen->isPossible(tile))
  1100. {
  1101. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1102. {
  1103. placeObject(gen, obj.first, tile);
  1104. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1105. result = true;
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. if (!result)
  1111. {
  1112. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1113. //TODO CLEANUP!
  1114. return false;
  1115. }
  1116. }
  1117. return true;
  1118. }
  1119. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1120. {
  1121. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  1122. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1123. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1124. minGuardedValue = minGuardedValues[monsterStrength];
  1125. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1126. {
  1127. return lhs.max > rhs.max;
  1128. };
  1129. //place biggest treasures first at large distance, place smaller ones inbetween
  1130. boost::sort(treasureInfo, valueComparator);
  1131. int totalDensity = 0;
  1132. for (auto t : treasureInfo)
  1133. {
  1134. totalDensity += t.density;
  1135. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1136. //also, normalize it to zone count - higher count means relatively smaller zones
  1137. //this is squared distance for optimization purposes
  1138. const double minDistance = std::max<float>((125.f / totalDensity), 2);
  1139. //distance lower than 2 causes objects to overlap and crash
  1140. do {
  1141. //optimization - don't check tiles which are not allowed
  1142. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1143. {
  1144. return !gen->isPossible(tile);
  1145. });
  1146. int3 pos;
  1147. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1148. if (!findPlaceForTreasurePile(gen, minDistance, pos, t.min))
  1149. {
  1150. break;
  1151. }
  1152. createTreasurePile(gen, pos, minDistance, t);
  1153. } while (true);
  1154. }
  1155. }
  1156. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1157. {
  1158. //tighten obstacles to improve visuals
  1159. for (int i = 0; i < 3; ++i)
  1160. {
  1161. int blockedTiles = 0;
  1162. int freeTiles = 0;
  1163. for (auto tile : tileinfo)
  1164. {
  1165. if (!gen->isPossible(tile)) //only possible tiles can change
  1166. continue;
  1167. int blockedNeighbours = 0;
  1168. int freeNeighbours = 0;
  1169. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1170. {
  1171. if (gen->isBlocked(pos))
  1172. blockedNeighbours++;
  1173. if (gen->isFree(pos))
  1174. freeNeighbours++;
  1175. });
  1176. if (blockedNeighbours > 4)
  1177. {
  1178. gen->setOccupied(tile, ETileType::BLOCKED);
  1179. blockedTiles++;
  1180. }
  1181. else if (freeNeighbours > 4)
  1182. {
  1183. gen->setOccupied(tile, ETileType::FREE);
  1184. freeTiles++;
  1185. }
  1186. }
  1187. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1188. }
  1189. #define MAKE_COOL_UNDERGROUND_TUNNELS false
  1190. if (pos.z && MAKE_COOL_UNDERGROUND_TUNNELS) //underground
  1191. {
  1192. std::vector<int3> rockTiles;
  1193. for (auto tile : tileinfo)
  1194. {
  1195. if (gen->shouldBeBlocked(tile))
  1196. {
  1197. bool placeRock = true;
  1198. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1199. {
  1200. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1201. placeRock = false;
  1202. });
  1203. if (placeRock)
  1204. {
  1205. rockTiles.push_back(tile);
  1206. }
  1207. }
  1208. }
  1209. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1210. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1211. for (auto tile : rockTiles)
  1212. {
  1213. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1214. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1215. //{
  1216. // if (!gen->isUsed(pos))
  1217. // gen->setOccupied (pos, ETileType::BLOCKED);
  1218. //});
  1219. }
  1220. }
  1221. typedef std::vector<ObjectTemplate> obstacleVector;
  1222. //obstacleVector possibleObstacles;
  1223. std::map <ui8, obstacleVector> obstaclesBySize;
  1224. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1225. std::vector<obstaclePair> possibleObstacles;
  1226. //get all possible obstacles for this terrain
  1227. for (auto primaryID : VLC->objtypeh->knownObjects())
  1228. {
  1229. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1230. {
  1231. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1232. if (handler->isStaticObject())
  1233. {
  1234. for (auto temp : handler->getTemplates())
  1235. {
  1236. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1237. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. for (auto o : obstaclesBySize)
  1243. {
  1244. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1245. }
  1246. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1247. {
  1248. return p1.first > p2.first; //bigger obstacles first
  1249. });
  1250. auto sel = gen->editManager->getTerrainSelection();
  1251. sel.clearSelection();
  1252. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1253. {
  1254. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1255. int3 obstaclePos = tile - temp.getBlockMapOffset();
  1256. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1257. {
  1258. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1259. placeObject(gen, obj, obstaclePos, false);
  1260. return true;
  1261. }
  1262. return false;
  1263. };
  1264. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1265. for (auto tile : boost::adaptors::reverse(tileinfo))
  1266. {
  1267. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1268. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1269. {
  1270. //start from biggets obstacles
  1271. for (int i = 0; i < possibleObstacles.size(); i++)
  1272. {
  1273. if (tryToPlaceObstacleHere(tile, i))
  1274. break;
  1275. }
  1276. }
  1277. }
  1278. }
  1279. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1280. {
  1281. initTerrainType(gen);
  1282. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1283. addAllPossibleObjects (gen);
  1284. placeMines(gen);
  1285. createRequiredObjects(gen);
  1286. fractalize(gen); //after required objects are created and linked with their own paths
  1287. createTreasures(gen);
  1288. createObstacles(gen);
  1289. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1290. return true;
  1291. }
  1292. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1293. {
  1294. float best_distance = 0;
  1295. bool result = false;
  1296. bool needsGuard = value > minGuardedValue;
  1297. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1298. for(auto tile : possibleTiles)
  1299. {
  1300. auto dist = gen->getNearestObjectDistance(tile);
  1301. if ((dist >= min_dist) && (dist > best_distance))
  1302. {
  1303. bool allTilesAvailable = true;
  1304. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1305. {
  1306. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1307. {
  1308. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1309. }
  1310. });
  1311. if (allTilesAvailable)
  1312. {
  1313. best_distance = dist;
  1314. pos = tile;
  1315. result = true;
  1316. }
  1317. }
  1318. }
  1319. if (result)
  1320. {
  1321. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1322. }
  1323. return result;
  1324. }
  1325. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1326. {
  1327. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1328. return false;
  1329. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1330. for (auto blockingTile : tilesBlockedByObject)
  1331. {
  1332. int3 t = pos + blockingTile;
  1333. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1334. {
  1335. return false; //if at least one tile is not possible, object can't be placed here
  1336. }
  1337. }
  1338. return true;
  1339. }
  1340. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1341. {
  1342. bool accessible = false;
  1343. for (int x = -1; x < 2; x++)
  1344. {
  1345. for (int y = -1; y <2; y++)
  1346. {
  1347. if (x && y) //check only if object is visitable from another tile
  1348. {
  1349. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1350. if (!vstd::contains(tilesBlockedByObject, offset))
  1351. {
  1352. int3 nearbyPos = tile + offset;
  1353. if (gen->map->isInTheMap(nearbyPos))
  1354. {
  1355. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1356. accessible = true;
  1357. }
  1358. }
  1359. }
  1360. };
  1361. }
  1362. return accessible;
  1363. }
  1364. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1365. {
  1366. if (obj->appearance.id == Obj::NO_OBJ)
  1367. {
  1368. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1369. if (templates.empty())
  1370. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1371. obj->appearance = templates.front();
  1372. }
  1373. }
  1374. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1375. {
  1376. for (auto blockingTile : tilesBlockedByObject)
  1377. {
  1378. int3 t = tile + blockingTile;
  1379. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1380. {
  1381. //if at least one tile is not possible, object can't be placed here
  1382. return false;
  1383. }
  1384. }
  1385. return true;
  1386. }
  1387. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1388. {
  1389. //we need object apperance to deduce free tile
  1390. setTemplateForObject(gen, obj);
  1391. //si32 min_dist = sqrt(tileinfo.size()/density);
  1392. int best_distance = 0;
  1393. bool result = false;
  1394. //si32 w = gen->map->width;
  1395. //si32 h = gen->map->height;
  1396. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1397. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1398. for (auto tile : tileinfo)
  1399. {
  1400. //object must be accessible from at least one surounding tile
  1401. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1402. continue;
  1403. auto ti = gen->getTile(tile);
  1404. auto dist = ti.getNearestObjectDistance();
  1405. //avoid borders
  1406. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1407. {
  1408. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1409. {
  1410. best_distance = dist;
  1411. pos = tile;
  1412. result = true;
  1413. }
  1414. }
  1415. }
  1416. if (result)
  1417. {
  1418. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1419. }
  1420. return result;
  1421. }
  1422. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1423. {
  1424. if (!gen->map->isInTheMap(pos))
  1425. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1426. object->pos = pos;
  1427. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1428. 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()));
  1429. for (auto tile : object->getBlockedPos())
  1430. {
  1431. if (!gen->map->isInTheMap(tile))
  1432. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1433. }
  1434. if (object->appearance.id == Obj::NO_OBJ)
  1435. {
  1436. auto terrainType = gen->map->getTile(pos).terType;
  1437. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1438. if (templates.empty())
  1439. 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));
  1440. object->appearance = templates.front();
  1441. }
  1442. gen->editManager->insertObject(object, pos);
  1443. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1444. }
  1445. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1446. {
  1447. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1448. checkAndPlaceObject (gen, object, pos);
  1449. auto points = object->getBlockedPos();
  1450. if (object->isVisitable())
  1451. points.insert(pos + object->getVisitableOffset());
  1452. points.insert(pos);
  1453. for(auto p : points)
  1454. {
  1455. if (gen->map->isInTheMap(p))
  1456. {
  1457. gen->setOccupied(p, ETileType::USED);
  1458. }
  1459. }
  1460. if (updateDistance)
  1461. {
  1462. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1463. {
  1464. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1465. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1466. }
  1467. }
  1468. }
  1469. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1470. {
  1471. placeObject(gen, object, pos);
  1472. guardObject(gen, object, str, zoneGuard);
  1473. }
  1474. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1475. {
  1476. //get all tiles from which this object can be accessed
  1477. int3 visitable = object->visitablePos();
  1478. std::vector<int3> tiles;
  1479. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1480. gen->foreach_neighbour(visitable, [&](int3& pos)
  1481. {
  1482. if (gen->isPossible(pos))
  1483. {
  1484. if (!vstd::contains(tilesBlockedByObject, pos))
  1485. {
  1486. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1487. {
  1488. tiles.push_back(pos);
  1489. }
  1490. }
  1491. };
  1492. });
  1493. return tiles;
  1494. }
  1495. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1496. {
  1497. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1498. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1499. int3 guardTile(-1,-1,-1);
  1500. for (auto tile : tiles)
  1501. {
  1502. //crunching path may fail if center of the zone is directly over wide object
  1503. //make sure object is accessible before surrounding it with blocked tiles
  1504. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1505. {
  1506. guardTile = tile;
  1507. break;
  1508. }
  1509. }
  1510. if (!guardTile.valid())
  1511. {
  1512. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1513. return false;
  1514. }
  1515. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1516. {
  1517. for (auto pos : tiles)
  1518. {
  1519. if (!gen->isFree(pos))
  1520. gen->setOccupied(pos, ETileType::BLOCKED);
  1521. }
  1522. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1523. {
  1524. if (gen->isPossible(pos))
  1525. gen->setOccupied (pos, ETileType::FREE);
  1526. });
  1527. gen->setOccupied (guardTile, ETileType::USED);
  1528. }
  1529. else //allow no guard or other object in front of this object
  1530. {
  1531. for (auto tile : tiles)
  1532. if (gen->isPossible(tile))
  1533. gen->setOccupied (tile, ETileType::FREE);
  1534. }
  1535. return true;
  1536. }
  1537. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1538. {
  1539. //int objectsVisitableFromBottom = 0; //for debug
  1540. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1541. ui32 total = 0;
  1542. //calculate actual treasure value range based on remaining value
  1543. ui32 maxVal = desiredValue - currentValue;
  1544. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1545. //roulette wheel
  1546. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1547. {
  1548. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1549. {
  1550. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1551. int3 newVisitablePos = info.nextTreasurePos;
  1552. if (!oi.templ.isVisitableFromTop())
  1553. {
  1554. //objectsVisitableFromBottom++;
  1555. //there must be free tiles under object
  1556. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1557. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1558. continue;
  1559. }
  1560. //NOTE: y coordinate grows downwards
  1561. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1562. {
  1563. bool fitsHere = false;
  1564. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1565. {
  1566. for (auto tile : info.visitableFromTopPositions)
  1567. {
  1568. int3 actualTile = tile + newVisitableOffset;
  1569. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1570. {
  1571. fitsHere = true;
  1572. break;
  1573. }
  1574. }
  1575. for (auto tile : info.visitableFromBottomPositions)
  1576. {
  1577. int3 actualTile = tile + newVisitableOffset;
  1578. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1579. {
  1580. fitsHere = true;
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. else //if new object is not visitable from top, it must be accessible from below or side
  1586. {
  1587. for (auto tile : info.visitableFromTopPositions)
  1588. {
  1589. int3 actualTile = tile + newVisitableOffset;
  1590. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1591. {
  1592. fitsHere = true;
  1593. break;
  1594. }
  1595. }
  1596. for (auto tile : info.visitableFromBottomPositions)
  1597. {
  1598. int3 actualTile = tile + newVisitableOffset;
  1599. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1600. {
  1601. fitsHere = true;
  1602. break;
  1603. }
  1604. }
  1605. }
  1606. if (!fitsHere)
  1607. continue;
  1608. }
  1609. //now check blockmap, including our already reserved pile area
  1610. bool fitsBlockmap = true;
  1611. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1612. blockedOffsets.insert (newVisitableOffset);
  1613. for (auto blockingTile : blockedOffsets)
  1614. {
  1615. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1616. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1617. {
  1618. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1619. break;
  1620. }
  1621. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1622. {
  1623. fitsBlockmap = false;
  1624. break;
  1625. }
  1626. }
  1627. if (!fitsBlockmap)
  1628. continue;
  1629. total += oi.probability;
  1630. //assert (oi.value > 0);
  1631. tresholds.push_back (std::make_pair (total, oi));
  1632. }
  1633. }
  1634. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1635. if (tresholds.empty())
  1636. {
  1637. ObjectInfo oi;
  1638. //Generate pandora Box with gold if the value is extremely high
  1639. if (minValue > 20000) //we don't have object valuable enough
  1640. {
  1641. oi.generateObject = [minValue]() -> CGObjectInstance *
  1642. {
  1643. auto obj = new CGPandoraBox();
  1644. obj->ID = Obj::PANDORAS_BOX;
  1645. obj->subID = 0;
  1646. obj->resources[Res::GOLD] = minValue;
  1647. return obj;
  1648. };
  1649. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1650. oi.value = minValue;
  1651. oi.probability = 0;
  1652. }
  1653. else //generate empty object with 0 value if the value if we can't spawn anything
  1654. {
  1655. oi.generateObject = [gen]() -> CGObjectInstance *
  1656. {
  1657. return nullptr;
  1658. };
  1659. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1660. oi.value = 0; // this field is checked to determine no object
  1661. oi.probability = 0;
  1662. }
  1663. return oi;
  1664. }
  1665. else
  1666. {
  1667. int r = gen->rand.nextInt (1, total);
  1668. for (auto t : tresholds)
  1669. {
  1670. if (r <= t.first)
  1671. return t.second;
  1672. }
  1673. assert (0); //we should never be here
  1674. }
  1675. //FIXME: control reaches end of non-void function. Missing return?
  1676. }
  1677. void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
  1678. {
  1679. ObjectInfo oi;
  1680. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1681. int numZones = gen->getZones().size();
  1682. for (auto primaryID : VLC->objtypeh->knownObjects())
  1683. {
  1684. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1685. {
  1686. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1687. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1688. {
  1689. for (auto temp : handler->getTemplates())
  1690. {
  1691. if (temp.canBePlacedAt(terrainType))
  1692. {
  1693. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1694. {
  1695. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1696. };
  1697. auto rmgInfo = handler->getRMGInfo();
  1698. oi.value = rmgInfo.value;
  1699. oi.probability = rmgInfo.rarity;
  1700. oi.templ = temp;
  1701. oi.maxPerZone = rmgInfo.zoneLimit;
  1702. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1703. possibleObjects.push_back(oi);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. //prisons
  1710. //levels 1, 5, 10, 20, 30
  1711. static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
  1712. static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
  1713. for (int i = 0; i < 5; i++)
  1714. {
  1715. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1716. {
  1717. auto obj = new CGHeroInstance;
  1718. obj->ID = Obj::PRISON;
  1719. std::vector<ui32> possibleHeroes;
  1720. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1721. {
  1722. if (gen->map->allowedHeroes[j])
  1723. possibleHeroes.push_back(j);
  1724. }
  1725. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1726. obj->subID = hid; //will be initialized later
  1727. obj->exp = prisonExp[i];
  1728. obj->setOwner(PlayerColor::NEUTRAL);
  1729. gen->map->allowedHeroes[hid] = false; //ban this hero
  1730. gen->decreasePrisonsRemaining();
  1731. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1732. return obj;
  1733. };
  1734. oi.setTemplate(Obj::PRISON, 0, terrainType);
  1735. oi.value = prisonValues[i];
  1736. oi.probability = 30;
  1737. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1738. possibleObjects.push_back(oi);
  1739. }
  1740. //all following objects are unlimited
  1741. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1742. //dwellings
  1743. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1744. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1745. static int elementalConfluxROE[] = { 7, 13, 16, 47 };
  1746. for (int i = 0; i < 4; i++)
  1747. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1748. for (auto secondaryID : subObjects)
  1749. {
  1750. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1751. auto creatures = dwellingHandler->getProducedCreatures();
  1752. if (creatures.empty())
  1753. continue;
  1754. auto cre = creatures.front();
  1755. if (cre->faction == townType)
  1756. {
  1757. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1758. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1759. oi.probability = 40;
  1760. for (auto temp : dwellingHandler->getTemplates())
  1761. {
  1762. if (temp.canBePlacedAt(terrainType))
  1763. {
  1764. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1765. {
  1766. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1767. //dwellingHandler->configureObject(obj, gen->rand);
  1768. obj->tempOwner = PlayerColor::NEUTRAL;
  1769. return obj;
  1770. };
  1771. oi.templ = temp;
  1772. possibleObjects.push_back(oi);
  1773. }
  1774. }
  1775. }
  1776. }
  1777. static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
  1778. for (int i = 0; i < 5; i++)
  1779. {
  1780. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1781. {
  1782. auto obj = new CGArtifact();
  1783. obj->ID = Obj::SPELL_SCROLL;
  1784. obj->subID = 0;
  1785. std::vector<SpellID> out;
  1786. //TODO: unify with cb->getAllowedSpells?
  1787. for (ui32 spellid = 0; spellid < gen->map->allowedSpell.size(); spellid++) //spellh size appears to be greater (?)
  1788. {
  1789. const CSpell *spell = SpellID(spellid).toSpell();
  1790. if (gen->map->allowedSpell[spell->id] && spell->level == i + 1)
  1791. {
  1792. out.push_back(spell->id);
  1793. }
  1794. }
  1795. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1796. gen->map->addNewArtifactInstance(a);
  1797. obj->storedArtifact = a;
  1798. return obj;
  1799. };
  1800. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  1801. oi.value = scrollValues[i];
  1802. oi.probability = 30;
  1803. possibleObjects.push_back(oi);
  1804. }
  1805. //pandora box with gold
  1806. for (int i = 1; i < 5; i++)
  1807. {
  1808. oi.generateObject = [i]() -> CGObjectInstance *
  1809. {
  1810. auto obj = new CGPandoraBox();
  1811. obj->ID = Obj::PANDORAS_BOX;
  1812. obj->subID = 0;
  1813. obj->resources[Res::GOLD] = i * 5000;
  1814. return obj;
  1815. };
  1816. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1817. oi.value = i * 5000;;
  1818. oi.probability = 5;
  1819. possibleObjects.push_back(oi);
  1820. }
  1821. //pandora box with experience
  1822. for (int i = 1; i < 5; i++)
  1823. {
  1824. oi.generateObject = [i]() -> CGObjectInstance *
  1825. {
  1826. auto obj = new CGPandoraBox();
  1827. obj->ID = Obj::PANDORAS_BOX;
  1828. obj->subID = 0;
  1829. obj->gainedExp = i * 5000;
  1830. return obj;
  1831. };
  1832. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1833. oi.value = i * 6000;;
  1834. oi.probability = 20;
  1835. possibleObjects.push_back(oi);
  1836. }
  1837. //pandora box with creatures
  1838. static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
  1839. auto creatureToCount = [](CCreature * creature) -> int
  1840. {
  1841. int actualTier = creature->level > 7 ? 6 : creature->level - 1;
  1842. float creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1843. if (creaturesAmount <= 5)
  1844. {
  1845. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1846. if (creaturesAmount < 1)
  1847. return 0;
  1848. }
  1849. else if (creaturesAmount <= 12)
  1850. {
  1851. (creaturesAmount /= 2) *= 2;
  1852. }
  1853. else if (creaturesAmount <= 50)
  1854. {
  1855. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1856. }
  1857. else
  1858. {
  1859. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1860. }
  1861. return creaturesAmount;
  1862. };
  1863. for (auto creature : VLC->creh->creatures)
  1864. {
  1865. if (!creature->special && creature->faction == townType)
  1866. {
  1867. int creaturesAmount = creatureToCount(creature);
  1868. if (!creaturesAmount)
  1869. continue;
  1870. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1871. {
  1872. auto obj = new CGPandoraBox();
  1873. obj->ID = Obj::PANDORAS_BOX;
  1874. obj->subID = 0;
  1875. auto stack = new CStackInstance(creature, creaturesAmount);
  1876. obj->creatures.putStack(SlotID(0), stack);
  1877. return obj;
  1878. };
  1879. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1880. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
  1881. oi.probability = 3;
  1882. possibleObjects.push_back(oi);
  1883. }
  1884. }
  1885. //Pandora with 12 spells of certain level
  1886. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1887. {
  1888. oi.generateObject = [i, 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() && spell->level == i)
  1897. spells.push_back(spell);
  1898. }
  1899. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1900. for (int j = 0; j < std::min<int>(12, 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 = (i + 1) * 2500; //5000 - 15000
  1908. oi.probability = 2;
  1909. possibleObjects.push_back(oi);
  1910. }
  1911. //Pandora with 15 spells of certain school
  1912. for (int i = 1; i <= 4; i++)
  1913. {
  1914. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1915. {
  1916. auto obj = new CGPandoraBox();
  1917. obj->ID = Obj::PANDORAS_BOX;
  1918. obj->subID = 0;
  1919. std::vector <CSpell *> spells;
  1920. for (auto spell : VLC->spellh->objects)
  1921. {
  1922. if (!spell->isSpecialSpell())
  1923. {
  1924. bool school = false; //TODO: we could have better interface for iterating schools
  1925. switch (i)
  1926. {
  1927. case 1:
  1928. school = spell->air;
  1929. break;
  1930. case 2:
  1931. school = spell->earth;
  1932. break;
  1933. case 3:
  1934. school = spell->fire;
  1935. break;
  1936. case 4:
  1937. school = spell->water;
  1938. break;
  1939. }
  1940. if (school)
  1941. spells.push_back(spell);
  1942. }
  1943. }
  1944. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1945. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1946. {
  1947. obj->spells.push_back(spells[j]->id);
  1948. }
  1949. return obj;
  1950. };
  1951. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1952. oi.value = 15000;
  1953. oi.probability = 2;
  1954. possibleObjects.push_back(oi);
  1955. }
  1956. // Pandora box with 60 random spells
  1957. oi.generateObject = [gen]() -> CGObjectInstance *
  1958. {
  1959. auto obj = new CGPandoraBox();
  1960. obj->ID = Obj::PANDORAS_BOX;
  1961. obj->subID = 0;
  1962. std::vector <CSpell *> spells;
  1963. for (auto spell : VLC->spellh->objects)
  1964. {
  1965. if (!spell->isSpecialSpell())
  1966. spells.push_back(spell);
  1967. }
  1968. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1969. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1970. {
  1971. obj->spells.push_back(spells[j]->id);
  1972. }
  1973. return obj;
  1974. };
  1975. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1976. oi.value = 3000;
  1977. oi.probability = 2;
  1978. possibleObjects.push_back(oi);
  1979. //seer huts with creatures or generic rewards
  1980. if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  1981. {
  1982. static const int genericSeerHuts = 8;
  1983. int seerHutsPerType = 0;
  1984. const int questArtsRemaining = gen->getQuestArtsRemaning().size();
  1985. std::vector<CCreature *> creatures;
  1986. for (auto cre : VLC->creh->creatures)
  1987. {
  1988. if (cre->faction == townType)
  1989. {
  1990. creatures.push_back(cre);
  1991. }
  1992. }
  1993. //general issue is that not many artifact types are available for quests
  1994. if (questArtsRemaining >= genericSeerHuts + creatures.size())
  1995. {
  1996. seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
  1997. }
  1998. else if (questArtsRemaining >= genericSeerHuts)
  1999. {
  2000. seerHutsPerType = 1;
  2001. }
  2002. oi.maxPerZone = seerHutsPerType;
  2003. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  2004. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  2005. {
  2006. ObjectInfo artInfo;
  2007. artInfo.probability = 1e6; //99,9% to spawn that art in first treasure pile
  2008. artInfo.maxPerZone = 1;
  2009. artInfo.value = 2000; //treasure art
  2010. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  2011. artInfo.generateObject = [id]() -> CGObjectInstance *
  2012. {
  2013. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  2014. return handler->create(handler->getTemplates().front());
  2015. };
  2016. return artInfo;
  2017. };
  2018. for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  2019. {
  2020. auto creature = creatures[i];
  2021. int creaturesAmount = creatureToCount(creature);
  2022. if (!creaturesAmount)
  2023. continue;
  2024. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2025. oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2026. {
  2027. auto obj = new CGSeerHut();
  2028. obj->ID = Obj::SEER_HUT;
  2029. obj->subID = randomAppearance;
  2030. obj->rewardType = CGSeerHut::CREATURE;
  2031. obj->rID = creature->idNumber;
  2032. obj->rVal = creaturesAmount;
  2033. obj->quest->missionType = CQuest::MISSION_ART;
  2034. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2035. obj->quest->m5arts.push_back(artid);
  2036. gen->banQuestArt(artid);
  2037. gen->map->addQuest(obj);
  2038. this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
  2039. return obj;
  2040. };
  2041. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2042. oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
  2043. oi.probability = 3;
  2044. possibleObjects.push_back(oi);
  2045. }
  2046. static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
  2047. static int seerValues[] = { 2000, 5333, 8666, 12000 };
  2048. for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
  2049. {
  2050. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2051. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2052. oi.value = seerValues[i];
  2053. oi.probability = 10;
  2054. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2055. {
  2056. auto obj = new CGSeerHut();
  2057. obj->ID = Obj::SEER_HUT;
  2058. obj->subID = randomAppearance;
  2059. obj->rewardType = CGSeerHut::EXPERIENCE;
  2060. obj->rID = 0; //unitialized?
  2061. obj->rVal = seerExpGold[i];
  2062. obj->quest->missionType = CQuest::MISSION_ART;
  2063. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2064. obj->quest->m5arts.push_back(artid);
  2065. gen->banQuestArt(artid);
  2066. gen->map->addQuest(obj);
  2067. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2068. return obj;
  2069. };
  2070. possibleObjects.push_back(oi);
  2071. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2072. {
  2073. auto obj = new CGSeerHut();
  2074. obj->ID = Obj::SEER_HUT;
  2075. obj->subID = randomAppearance;
  2076. obj->rewardType = CGSeerHut::RESOURCES;
  2077. obj->rID = Res::GOLD;
  2078. obj->rVal = seerExpGold[i];
  2079. obj->quest->missionType = CQuest::MISSION_ART;
  2080. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2081. obj->quest->m5arts.push_back(artid);
  2082. gen->banQuestArt(artid);
  2083. gen->map->addQuest(obj);
  2084. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2085. return obj;
  2086. };
  2087. possibleObjects.push_back(oi);
  2088. }
  2089. }
  2090. }
  2091. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2092. {
  2093. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  2094. }