CRmgTemplateZone.cpp 80 KB

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