CRmgTemplateZone.cpp 72 KB

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