CRmgTemplateZone.cpp 67 KB

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