CRmgTemplateZone.cpp 82 KB

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