CRmgTemplateZone.cpp 96 KB

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