CRmgTemplateZone.cpp 81 KB

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