CRmgTemplateZone.cpp 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346
  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(ETerrainType::WRONG),roadType(ERoadType::NO_ROAD)
  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 != ERoadType::NO_ROAD;
  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. ETerrainType CTileInfo::getTerrainType() const
  75. {
  76. return terrain;
  77. }
  78. void CTileInfo::setTerrainType(ETerrainType value)
  79. {
  80. terrain = value;
  81. }
  82. void CTileInfo::setRoadType(ERoadType::ERoadType value)
  83. {
  84. roadType = value;
  85. // setOccupied(ETileType::FREE);
  86. }
  87. CRmgTemplateZone::CRmgTemplateZone(CMapGenerator * Gen)
  88. : ZoneOptions(),
  89. townType(ETownType::NEUTRAL),
  90. terrainType (ETerrainType::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, ERoadType::NO_ROAD); //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, ERoadType::COBBLESTONE_ROAD);
  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. bool CRmgTemplateZone::addMonster(int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  1098. {
  1099. //precalculate actual (randomized) monster strength based on this post
  1100. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  1101. int mapMonsterStrength = gen->getMapGenOptions().getMonsterStrength();
  1102. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  1103. static const int value1[] = {2500, 1500, 1000, 500, 0};
  1104. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  1105. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  1106. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  1107. int strength1 = static_cast<int>(std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]));
  1108. int strength2 = static_cast<int>(std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]));
  1109. strength = strength1 + strength2;
  1110. if (strength < gen->getConfig().minGuardStrength)
  1111. return false; //no guard at all
  1112. CreatureID creId = CreatureID::NONE;
  1113. int amount = 0;
  1114. std::vector<CreatureID> possibleCreatures;
  1115. for (auto cre : VLC->creh->objects)
  1116. {
  1117. if (cre->special)
  1118. continue;
  1119. if (!cre->AIValue) //bug #2681
  1120. continue;
  1121. if (!vstd::contains(monsterTypes, cre->faction))
  1122. continue;
  1123. 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
  1124. {
  1125. possibleCreatures.push_back(cre->idNumber);
  1126. }
  1127. }
  1128. if (possibleCreatures.size())
  1129. {
  1130. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  1131. amount = strength / VLC->creh->objects[creId]->AIValue;
  1132. if (amount >= 4)
  1133. amount = static_cast<int>(amount * gen->rand.nextDouble(0.75, 1.25));
  1134. }
  1135. else //just pick any available creature
  1136. {
  1137. creId = CreatureID(132); //Azure Dragon
  1138. amount = strength / VLC->creh->objects[creId]->AIValue;
  1139. }
  1140. auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  1141. auto guard = (CGCreature *) guardFactory->create(ObjectTemplate());
  1142. guard->character = CGCreature::HOSTILE;
  1143. auto hlp = new CStackInstance(creId, amount);
  1144. //will be set during initialization
  1145. guard->putStack(SlotID(0), hlp);
  1146. placeObject(guard, pos);
  1147. if (clearSurroundingTiles)
  1148. {
  1149. //do not spawn anything near monster
  1150. gen->foreach_neighbour (pos, [this](int3 pos)
  1151. {
  1152. if (gen->isPossible(pos))
  1153. gen->setOccupied(pos, ETileType::FREE);
  1154. });
  1155. }
  1156. return true;
  1157. }
  1158. bool CRmgTemplateZone::createTreasurePile(int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  1159. {
  1160. CTreasurePileInfo info;
  1161. std::map<int3, CGObjectInstance *> treasures;
  1162. std::set<int3> boundary;
  1163. int3 guardPos (-1,-1,-1);
  1164. info.nextTreasurePos = pos;
  1165. int maxValue = treasureInfo.max;
  1166. int minValue = treasureInfo.min;
  1167. ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
  1168. int currentValue = 0;
  1169. CGObjectInstance * object = nullptr;
  1170. while (currentValue <= (int)desiredValue - 100) //no objects with value below 100 are available
  1171. {
  1172. treasures[info.nextTreasurePos] = nullptr;
  1173. for (auto treasurePos : treasures)
  1174. {
  1175. gen->foreach_neighbour(treasurePos.first, [&boundary](int3 pos)
  1176. {
  1177. boundary.insert(pos);
  1178. });
  1179. }
  1180. for (auto treasurePos : treasures)
  1181. {
  1182. //leaving only boundary around objects
  1183. vstd::erase_if_present(boundary, treasurePos.first);
  1184. }
  1185. for (auto tile : boundary)
  1186. {
  1187. //we can't extend boundary anymore
  1188. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  1189. break;
  1190. }
  1191. ObjectInfo oi = getRandomObject(info, desiredValue, maxValue, currentValue);
  1192. if (!oi.value) //0 value indicates no object
  1193. {
  1194. vstd::erase_if_present(treasures, info.nextTreasurePos);
  1195. break;
  1196. }
  1197. else
  1198. {
  1199. object = oi.generateObject();
  1200. object->appearance = oi.templ;
  1201. //remove from possible objects
  1202. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  1203. assert (oiptr != possibleObjects.end());
  1204. oiptr->maxPerZone--;
  1205. if (!oiptr->maxPerZone)
  1206. possibleObjects.erase(oiptr);
  1207. //update treasure pile area
  1208. int3 visitablePos = info.nextTreasurePos;
  1209. if (oi.templ.isVisitableFromTop())
  1210. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  1211. else
  1212. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  1213. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  1214. {
  1215. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  1216. info.occupiedPositions.insert(blockPos);
  1217. info.blockedPositions.insert(blockPos);
  1218. }
  1219. info.occupiedPositions.insert(visitablePos + oi.templ.getVisitableOffset());
  1220. currentValue += oi.value;
  1221. treasures[info.nextTreasurePos] = object;
  1222. //now find place for next object
  1223. int3 placeFound(-1,-1,-1);
  1224. //randomize next position from among possible ones
  1225. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  1226. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  1227. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  1228. {
  1229. return lhs.y < rhs.y;
  1230. };
  1231. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  1232. for (auto tile : boundaryCopy)
  1233. {
  1234. if (gen->isPossible(tile) && gen->getZoneID(tile) == getId()) //we can place new treasure only on possible tile
  1235. {
  1236. bool here = true;
  1237. gen->foreach_neighbour (tile, [this, &here, minDistance](int3 pos)
  1238. {
  1239. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getZoneID(pos) != getId() || gen->getNearestObjectDistance(pos) < minDistance)
  1240. here = false;
  1241. });
  1242. if (here)
  1243. {
  1244. placeFound = tile;
  1245. break;
  1246. }
  1247. }
  1248. }
  1249. if (placeFound.valid())
  1250. info.nextTreasurePos = placeFound;
  1251. else
  1252. break; //no more place to add any objects
  1253. }
  1254. }
  1255. if (treasures.size())
  1256. {
  1257. //find object closest to free path, then connect it to the middle of the zone
  1258. int3 closestTile = int3(-1,-1,-1);
  1259. float minTreasureDistance = 1e10;
  1260. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  1261. {
  1262. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  1263. if (closestFreeTile.dist2d(visitablePos) < minTreasureDistance)
  1264. {
  1265. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map, to not make path up through it
  1266. minTreasureDistance = static_cast<float>(closestFreeTile.dist2d(visitablePos));
  1267. }
  1268. }
  1269. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  1270. {
  1271. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  1272. if (closestFreeTile.dist2d(visitablePos) < minTreasureDistance)
  1273. {
  1274. closestTile = visitablePos;
  1275. minTreasureDistance = static_cast<float>(closestFreeTile.dist2d(visitablePos));
  1276. }
  1277. }
  1278. assert (closestTile.valid());
  1279. for (auto tile : info.occupiedPositions)
  1280. {
  1281. if (gen->map->isInTheMap(tile) && gen->isPossible(tile) && gen->getZoneID(tile)==id) //pile boundary may reach map border
  1282. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  1283. }
  1284. if (!connectPath (closestTile, false)) //this place is sealed off, need to find new position
  1285. {
  1286. return false;
  1287. }
  1288. //update boundary around our objects, including knowledge about objects visitable from bottom
  1289. boundary.clear();
  1290. for (auto tile : info.visitableFromBottomPositions)
  1291. {
  1292. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  1293. {
  1294. if (pos.y >= tile.y) //don't block these objects from above
  1295. boundary.insert(pos);
  1296. });
  1297. }
  1298. for (auto tile : info.visitableFromTopPositions)
  1299. {
  1300. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  1301. {
  1302. boundary.insert(pos);
  1303. });
  1304. }
  1305. bool isPileGuarded = isGuardNeededForTreasure(currentValue);
  1306. for (auto tile : boundary) //guard must be standing there
  1307. {
  1308. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  1309. {
  1310. guardPos = tile;
  1311. break;
  1312. }
  1313. }
  1314. if (guardPos.valid())
  1315. {
  1316. for (auto treasure : treasures)
  1317. {
  1318. int3 visitableOffset = treasure.second->getVisitableOffset();
  1319. placeObject(treasure.second, treasure.first + visitableOffset);
  1320. }
  1321. if (isPileGuarded && addMonster(guardPos, currentValue, false))
  1322. {//block only if the object is guarded
  1323. for (auto tile : boundary)
  1324. {
  1325. if (gen->isPossible(tile))
  1326. gen->setOccupied(tile, ETileType::BLOCKED);
  1327. }
  1328. //do not spawn anything near monster
  1329. gen->foreach_neighbour(guardPos, [this](int3 pos)
  1330. {
  1331. if (gen->isPossible(pos))
  1332. gen->setOccupied(pos, ETileType::FREE);
  1333. });
  1334. }
  1335. }
  1336. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  1337. {
  1338. for (auto treasure : treasures)
  1339. {
  1340. if (gen->isPossible(treasure.first))
  1341. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  1342. delete treasure.second;
  1343. }
  1344. }
  1345. return true;
  1346. }
  1347. else //we did not place eveyrthing successfully
  1348. {
  1349. if(gen->isPossible(pos))
  1350. gen->setOccupied(pos, ETileType::BLOCKED); //TODO: refactor stop condition
  1351. vstd::erase_if_present(possibleTiles, pos);
  1352. return false;
  1353. }
  1354. }
  1355. void CRmgTemplateZone::initTownType ()
  1356. {
  1357. //FIXME: handle case that this player is not present -> towns should be set to neutral
  1358. int totalTowns = 0;
  1359. //cut a ring around town to ensure crunchPath always hits it.
  1360. auto cutPathAroundTown = [this](const CGTownInstance * town)
  1361. {
  1362. auto clearPos = [this](const int3 & pos)
  1363. {
  1364. if (gen->isPossible(pos))
  1365. gen->setOccupied(pos, ETileType::FREE);
  1366. };
  1367. for (auto blockedTile : town->getBlockedPos())
  1368. {
  1369. gen->foreach_neighbour(blockedTile, clearPos);
  1370. }
  1371. //clear town entry
  1372. gen->foreach_neighbour(town->visitablePos()+int3{0,1,0}, clearPos);
  1373. };
  1374. auto addNewTowns = [&totalTowns, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  1375. {
  1376. for (int i = 0; i < count; i++)
  1377. {
  1378. si32 subType = townType;
  1379. if(totalTowns>0)
  1380. {
  1381. if(!this->townsAreSameType)
  1382. {
  1383. if (townTypes.size())
  1384. subType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1385. else
  1386. subType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  1387. }
  1388. }
  1389. auto townFactory = VLC->objtypeh->getHandlerFor(Obj::TOWN, subType);
  1390. auto town = (CGTownInstance *) townFactory->create(ObjectTemplate());
  1391. town->ID = Obj::TOWN;
  1392. town->tempOwner = player;
  1393. if (hasFort)
  1394. town->builtBuildings.insert(BuildingID::FORT);
  1395. town->builtBuildings.insert(BuildingID::DEFAULT);
  1396. for(auto spell : VLC->spellh->objects) //add all regular spells to town
  1397. {
  1398. if(!spell->isSpecial() && !spell->isCreatureAbility())
  1399. town->possibleSpells.push_back(spell->id);
  1400. }
  1401. if (totalTowns <= 0)
  1402. {
  1403. //FIXME: discovered bug with small zones - getPos is close to map boarder and we have outOfMap exception
  1404. //register MAIN town of zone
  1405. gen->registerZone(town->subID);
  1406. //first town in zone goes in the middle
  1407. placeObject(town, getPos() + town->getVisitableOffset(), true);
  1408. cutPathAroundTown(town);
  1409. setPos(town->visitablePos()); //roads lead to mian town
  1410. }
  1411. else
  1412. addRequiredObject (town);
  1413. totalTowns++;
  1414. }
  1415. };
  1416. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  1417. {
  1418. //set zone types to player faction, generate main town
  1419. logGlobal->info("Preparing playing zone");
  1420. int player_id = *owner - 1;
  1421. auto & playerInfo = gen->map->players[player_id];
  1422. PlayerColor player(player_id);
  1423. if (playerInfo.canAnyonePlay())
  1424. {
  1425. player = PlayerColor(player_id);
  1426. townType = gen->getMapGenOptions().getPlayersSettings().find(player)->second.getStartingTown();
  1427. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  1428. randomizeTownType(true);
  1429. }
  1430. else //no player - randomize town
  1431. {
  1432. player = PlayerColor::NEUTRAL;
  1433. randomizeTownType();
  1434. }
  1435. auto townFactory = VLC->objtypeh->getHandlerFor(Obj::TOWN, townType);
  1436. CGTownInstance * town = (CGTownInstance *) townFactory->create(ObjectTemplate());
  1437. town->tempOwner = player;
  1438. town->builtBuildings.insert(BuildingID::FORT);
  1439. town->builtBuildings.insert(BuildingID::DEFAULT);
  1440. for(auto spell : VLC->spellh->objects) //add all regular spells to town
  1441. {
  1442. if(!spell->isSpecial() && !spell->isCreatureAbility())
  1443. town->possibleSpells.push_back(spell->id);
  1444. }
  1445. //towns are big objects and should be centered around visitable position
  1446. placeObject(town, getPos() + town->getVisitableOffset(), true);
  1447. cutPathAroundTown(town);
  1448. setPos(town->visitablePos()); //roads lead to mian town
  1449. totalTowns++;
  1450. //register MAIN town of zone only
  1451. gen->registerZone (town->subID);
  1452. if (playerInfo.canAnyonePlay()) //configure info for owning player
  1453. {
  1454. logGlobal->trace("Fill player info %d", player_id);
  1455. // Update player info
  1456. playerInfo.allowedFactions.clear();
  1457. playerInfo.allowedFactions.insert(townType);
  1458. playerInfo.hasMainTown = true;
  1459. playerInfo.posOfMainTown = town->pos;
  1460. playerInfo.generateHeroAtMainTown = true;
  1461. //now create actual towns
  1462. addNewTowns(playerTowns.getCastleCount() - 1, true, player);
  1463. addNewTowns(playerTowns.getTownCount(), false, player);
  1464. }
  1465. else
  1466. {
  1467. addNewTowns(playerTowns.getCastleCount() - 1, true, PlayerColor::NEUTRAL);
  1468. addNewTowns(playerTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1469. }
  1470. }
  1471. else //randomize town types for any other zones as well
  1472. {
  1473. randomizeTownType();
  1474. }
  1475. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  1476. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1477. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  1478. {
  1479. //25% chance for neutral
  1480. if (gen->rand.nextInt(1, 100) <= 25)
  1481. {
  1482. townType = ETownType::NEUTRAL;
  1483. }
  1484. else
  1485. {
  1486. if (townTypes.size())
  1487. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1488. else if (monsterTypes.size())
  1489. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  1490. else //just in any case
  1491. randomizeTownType();
  1492. }
  1493. }
  1494. }
  1495. void CRmgTemplateZone::randomizeTownType(bool matchUndergroundType)
  1496. {
  1497. auto townTypesAllowed = (townTypes.size() ? townTypes : getDefaultTownTypes());
  1498. if(matchUndergroundType && gen->getMapGenOptions().getHasTwoLevels())
  1499. {
  1500. std::set<TFaction> townTypesVerify;
  1501. for(TFaction factionIdx : townTypesAllowed)
  1502. {
  1503. bool preferUnderground = (*VLC->townh)[factionIdx]->preferUndergroundPlacement;
  1504. if(isUnderground() ? preferUnderground : !preferUnderground)
  1505. {
  1506. townTypesVerify.insert(factionIdx);
  1507. }
  1508. }
  1509. if(!townTypesVerify.empty())
  1510. townTypesAllowed = townTypesVerify;
  1511. }
  1512. townType = *RandomGeneratorUtil::nextItem(townTypesAllowed, gen->rand);
  1513. }
  1514. void CRmgTemplateZone::initTerrainType ()
  1515. {
  1516. if (type==ETemplateZoneType::WATER)
  1517. {
  1518. terrainType = ETerrainType::WATER;
  1519. }
  1520. else
  1521. {
  1522. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  1523. terrainType = (*VLC->townh)[townType]->nativeTerrain;
  1524. else
  1525. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  1526. //TODO: allow new types of terrain?
  1527. {
  1528. if(isUnderground())
  1529. {
  1530. if(!vstd::contains(gen->getConfig().terrainUndergroundAllowed, terrainType))
  1531. terrainType = ETerrainType::SUBTERRANEAN;
  1532. }
  1533. else
  1534. {
  1535. if(vstd::contains(gen->getConfig().terrainGroundProhibit, terrainType))
  1536. terrainType = ETerrainType::DIRT;
  1537. }
  1538. }
  1539. }
  1540. paintZoneTerrain (terrainType);
  1541. }
  1542. void CRmgTemplateZone::paintZoneTerrain (ETerrainType terrainType)
  1543. {
  1544. std::vector<int3> tiles(tileinfo.begin(), tileinfo.end());
  1545. gen->getEditManager()->getTerrainSelection().setSelection(tiles);
  1546. gen->getEditManager()->drawTerrain(terrainType, &gen->rand);
  1547. }
  1548. bool CRmgTemplateZone::placeMines ()
  1549. {
  1550. using namespace Res;
  1551. std::vector<CGMine*> createdMines;
  1552. for(const auto & mineInfo : mines)
  1553. {
  1554. ERes res = (ERes)mineInfo.first;
  1555. for(int i = 0; i < mineInfo.second; ++i)
  1556. {
  1557. auto mine = (CGMine*) VLC->objtypeh->getHandlerFor(Obj::MINE, res)->create(ObjectTemplate());
  1558. mine->producedResource = res;
  1559. mine->tempOwner = PlayerColor::NEUTRAL;
  1560. mine->producedQuantity = mine->defaultResProduction();
  1561. createdMines.push_back(mine);
  1562. if(!i && (res == ERes::WOOD || res == ERes::ORE))
  1563. addCloseObject(mine, gen->getConfig().mineValues.at(res)); //only first wood&ore mines are close
  1564. else
  1565. addRequiredObject(mine, gen->getConfig().mineValues.at(res));
  1566. }
  1567. }
  1568. //create extra resources
  1569. if(int extraRes = gen->getConfig().mineExtraResources)
  1570. {
  1571. for(auto * mine : createdMines)
  1572. {
  1573. for(int rc = gen->rand.nextInt(1, extraRes); rc > 0; --rc)
  1574. {
  1575. auto resourse = (CGResource*) VLC->objtypeh->getHandlerFor(Obj::RESOURCE, mine->producedResource)->create(ObjectTemplate());
  1576. resourse->amount = CGResource::RANDOM_AMOUNT;
  1577. addNearbyObject(resourse, mine);
  1578. }
  1579. }
  1580. }
  1581. return true;
  1582. }
  1583. EObjectPlacingResult::EObjectPlacingResult CRmgTemplateZone::tryToPlaceObjectAndConnectToPath(CGObjectInstance * obj, const int3 & pos)
  1584. {
  1585. //check if we can find a path around this object. Tiles will be set to "USED" after object is successfully placed.
  1586. obj->pos = pos;
  1587. gen->setOccupied(obj->visitablePos(), ETileType::BLOCKED);
  1588. for (auto tile : obj->getBlockedPos())
  1589. {
  1590. if (gen->map->isInTheMap(tile))
  1591. gen->setOccupied(tile, ETileType::BLOCKED);
  1592. }
  1593. int3 accessibleOffset = getAccessibleOffset(obj->appearance, pos);
  1594. if (!accessibleOffset.valid())
  1595. {
  1596. logGlobal->warn("Cannot access required object at position %s, retrying", pos.toString());
  1597. return EObjectPlacingResult::CANNOT_FIT;
  1598. }
  1599. if (!connectPath(accessibleOffset, true))
  1600. {
  1601. logGlobal->trace("Failed to create path to required object at position %s, retrying", pos.toString());
  1602. return EObjectPlacingResult::SEALED_OFF;
  1603. }
  1604. else
  1605. return EObjectPlacingResult::SUCCESS;
  1606. }
  1607. bool CRmgTemplateZone::createRequiredObjects()
  1608. {
  1609. logGlobal->trace("Creating required objects");
  1610. for(const auto &object : requiredObjects)
  1611. {
  1612. auto obj = object.first;
  1613. int3 pos;
  1614. while (true)
  1615. {
  1616. if (!findPlaceForObject(obj, 3, pos))
  1617. {
  1618. logGlobal->error("Failed to fill zone %d due to lack of space", id);
  1619. return false;
  1620. }
  1621. if (tryToPlaceObjectAndConnectToPath(obj, pos) == EObjectPlacingResult::SUCCESS)
  1622. {
  1623. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1624. placeObject(obj, pos);
  1625. guardObject(obj, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY), true);
  1626. break;
  1627. }
  1628. }
  1629. }
  1630. for (const auto &obj : closeObjects)
  1631. {
  1632. setTemplateForObject(obj.first);
  1633. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1634. bool finished = false;
  1635. bool attempt = true;
  1636. while (!finished && attempt)
  1637. {
  1638. attempt = false;
  1639. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end());
  1640. //new tiles vector after each object has been placed, OR misplaced area has been sealed off
  1641. boost::remove_if(tiles, [obj, this](int3 &tile)-> bool
  1642. {
  1643. //object must be accessible from at least one surounding tile
  1644. return !this->isAccessibleFromSomewhere(obj.first->appearance, tile);
  1645. });
  1646. auto targetPosition = requestedPositions.find(obj.first)!=requestedPositions.end() ? requestedPositions[obj.first] : pos;
  1647. // smallest distance to zone center, greatest distance to nearest object
  1648. auto isCloser = [this, &targetPosition, &tilesBlockedByObject](const int3 & lhs, const int3 & rhs) -> bool
  1649. {
  1650. float lDist = std::numeric_limits<float>::max();
  1651. float rDist = std::numeric_limits<float>::max();
  1652. for(int3 t : tilesBlockedByObject)
  1653. {
  1654. t += targetPosition;
  1655. lDist = fmin(lDist, static_cast<float>(t.dist2d(lhs)));
  1656. rDist = fmin(rDist, static_cast<float>(t.dist2d(rhs)));
  1657. }
  1658. lDist *= (lDist > 12) ? 10 : 1; //objects within 12 tile radius are preferred (smaller distance rating)
  1659. rDist *= (rDist > 12) ? 10 : 1;
  1660. return (lDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(lhs))) < (rDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(rhs)));
  1661. };
  1662. boost::sort(tiles, isCloser);
  1663. if (tiles.empty())
  1664. {
  1665. logGlobal->error("Failed to fill zone %d due to lack of space", id);
  1666. return false;
  1667. }
  1668. for (auto tile : tiles)
  1669. {
  1670. //code partially adapted from findPlaceForObject()
  1671. if(!areAllTilesAvailable(obj.first, tile, tilesBlockedByObject))
  1672. continue;
  1673. attempt = true;
  1674. EObjectPlacingResult::EObjectPlacingResult result = tryToPlaceObjectAndConnectToPath(obj.first, tile);
  1675. if (result == EObjectPlacingResult::SUCCESS)
  1676. {
  1677. placeObject(obj.first, tile);
  1678. guardObject(obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1679. finished = true;
  1680. break;
  1681. }
  1682. else if (result == EObjectPlacingResult::CANNOT_FIT)
  1683. continue; // next tile
  1684. else if (result == EObjectPlacingResult::SEALED_OFF)
  1685. {
  1686. break; //tiles expired, pick new ones
  1687. }
  1688. else
  1689. throw (rmgException("Wrong result of tryToPlaceObjectAndConnectToPath()"));
  1690. }
  1691. }
  1692. }
  1693. //create nearby objects (e.g. extra resources close to mines)
  1694. for(const auto & object : nearbyObjects)
  1695. {
  1696. auto obj = object.first;
  1697. std::set<int3> possiblePositions;
  1698. for (auto blockedTile : object.second->getBlockedPos())
  1699. {
  1700. gen->foreachDirectNeighbour(blockedTile, [this, &possiblePositions](int3 pos)
  1701. {
  1702. if (!gen->isBlocked(pos) && tileinfo.count(pos))
  1703. {
  1704. //some resources still could be unaccessible, at least one free cell shall be
  1705. gen->foreach_neighbour(pos, [this, &possiblePositions, &pos](int3 p)
  1706. {
  1707. if(gen->isFree(p))
  1708. possiblePositions.insert(pos);
  1709. });
  1710. }
  1711. });
  1712. }
  1713. if(possiblePositions.empty())
  1714. {
  1715. delete obj; //is it correct way to prevent leak?
  1716. }
  1717. else
  1718. {
  1719. auto pos = *RandomGeneratorUtil::nextItem(possiblePositions, gen->rand);
  1720. placeObject(obj, pos);
  1721. }
  1722. }
  1723. //create object on specific positions
  1724. //TODO: implement guards
  1725. for (const auto &obj : instantObjects)
  1726. {
  1727. if(tryToPlaceObjectAndConnectToPath(obj.first, obj.second)==EObjectPlacingResult::SUCCESS)
  1728. {
  1729. placeObject(obj.first, obj.second);
  1730. //TODO: guardObject(...)
  1731. }
  1732. }
  1733. requiredObjects.clear();
  1734. closeObjects.clear();
  1735. nearbyObjects.clear();
  1736. instantObjects.clear();
  1737. return true;
  1738. }
  1739. int3 CRmgTemplateZone::makeBoat(TRmgTemplateZoneId land, const std::set<int3> & lake)
  1740. {
  1741. std::set<int3> lakeCoast;
  1742. std::set_intersection(gen->getZones()[land]->getCoastTiles().begin(), gen->getZones()[land]->getCoastTiles().end(), lake.begin(), lake.end(), std::inserter(lakeCoast, lakeCoast.begin()));
  1743. for(int randomAttempts = 0; randomAttempts<5; ++randomAttempts)
  1744. {
  1745. auto coastTile = *RandomGeneratorUtil::nextItem(lakeCoast, gen->rand);
  1746. if(gen->getZoneID(coastTile) == gen->getZoneWater().first && isWaterConnected(land, coastTile) && makeBoat(land, coastTile))
  1747. return coastTile;
  1748. }
  1749. //if no success on random selection, use brute force
  1750. for(const auto& coastTile : lakeCoast)
  1751. {
  1752. if(gen->getZoneID(coastTile) == gen->getZoneWater().first && isWaterConnected(land, coastTile) && makeBoat(land, coastTile))
  1753. return coastTile;
  1754. }
  1755. return int3(-1,-1,-1);
  1756. }
  1757. bool CRmgTemplateZone::makeBoat(TRmgTemplateZoneId land, const int3 & coast)
  1758. {
  1759. //verify coast
  1760. if(gen->getZoneWater().first != id)
  1761. throw rmgException("Cannot make a ship: not a water zone");
  1762. if(gen->getZoneID(coast) != id)
  1763. throw rmgException("Cannot make a ship: coast tile doesn't belong to water");
  1764. //find zone for ship boarding
  1765. std::vector<int3> landTiles;
  1766. gen->foreach_neighbour(coast, [this, &landTiles, land](const int3 & t)
  1767. {
  1768. if(land == gen->getZoneID(t) && gen->isPossible(t))
  1769. {
  1770. landTiles.push_back(t);
  1771. }
  1772. });
  1773. if(landTiles.empty())
  1774. return false;
  1775. int3 landTile = {-1, -1, -1};
  1776. for(auto& lt : landTiles)
  1777. {
  1778. if(gen->getZones()[land]->connectPath(lt, false))
  1779. {
  1780. landTile = lt;
  1781. gen->setOccupied(landTile, ETileType::FREE);
  1782. break;
  1783. }
  1784. }
  1785. if(!landTile.valid())
  1786. return false;
  1787. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::BOAT);
  1788. auto* boat = (CGBoat*)VLC->objtypeh->getHandlerFor(Obj::BOAT, *RandomGeneratorUtil::nextItem(subObjects, gen->rand))->create(ObjectTemplate());
  1789. auto targetPos = boat->getVisitableOffset() + coast + int3{1, 0, 0}; //+1 offset for boat - bug?
  1790. if (gen->map->isInTheMap(targetPos) && gen->isPossible(targetPos) && gen->getZoneID(targetPos) == getId())
  1791. {
  1792. //don't connect to path because it's not initialized
  1793. addObjectAtPosition(boat, targetPos);
  1794. gen->setOccupied(targetPos, ETileType::USED);
  1795. return true;
  1796. }
  1797. return false;
  1798. }
  1799. int3 CRmgTemplateZone::createShipyard(const std::set<int3> & lake, si32 guardStrength)
  1800. {
  1801. std::set<int3> lakeCoast;
  1802. std::set_intersection(getCoastTiles().begin(), getCoastTiles().end(), lake.begin(), lake.end(), std::inserter(lakeCoast, lakeCoast.begin()));
  1803. for(int randomAttempts = 0; randomAttempts < 5; ++randomAttempts)
  1804. {
  1805. auto coastTile = *RandomGeneratorUtil::nextItem(lakeCoast, gen->rand);
  1806. if(gen->getZoneID(coastTile) == gen->getZoneWater().first && isWaterConnected(id, coastTile) && createShipyard(coastTile, guardStrength))
  1807. return coastTile;
  1808. }
  1809. //if no success on random selection, use brute force
  1810. for(const auto& coastTile : lakeCoast)
  1811. {
  1812. if(gen->getZoneID(coastTile) == gen->getZoneWater().first && isWaterConnected(id, coastTile) && createShipyard(coastTile, guardStrength))
  1813. return coastTile;
  1814. }
  1815. return int3(-1,-1,-1);
  1816. }
  1817. bool CRmgTemplateZone::createShipyard(const int3 & position, si32 guardStrength)
  1818. {
  1819. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::SHIPYARD);
  1820. auto shipyard = (CGShipyard*) VLC->objtypeh->getHandlerFor(Obj::SHIPYARD, *RandomGeneratorUtil::nextItem(subObjects, gen->rand))->create(ObjectTemplate());
  1821. shipyard->tempOwner = PlayerColor::NEUTRAL;
  1822. setTemplateForObject(shipyard);
  1823. std::vector<int3> outOffsets;
  1824. auto tilesBlockedByObject = shipyard->getBlockedOffsets();
  1825. tilesBlockedByObject.insert(shipyard->getVisitableOffset());
  1826. shipyard->getOutOffsets(outOffsets);
  1827. int3 targetTile(-1, -1, -1);
  1828. std::set<int3> shipAccessCandidates;
  1829. for(const auto & outOffset : outOffsets)
  1830. {
  1831. auto candidateTile = position - outOffset;
  1832. std::set<int3> tilesBlockedAbsolute;
  1833. //check space under object
  1834. bool allClear = true;
  1835. for(const auto & objectTileOffset : tilesBlockedByObject)
  1836. {
  1837. auto objectTile = candidateTile + objectTileOffset;
  1838. tilesBlockedAbsolute.insert(objectTile);
  1839. if(!gen->map->isInTheMap(objectTile) || !gen->isPossible(objectTile) || gen->getZoneID(objectTile)!=id)
  1840. {
  1841. allClear = false;
  1842. break;
  1843. }
  1844. }
  1845. if(!allClear) //cannot place shipyard anyway
  1846. continue;
  1847. //prepare temporary map
  1848. for(auto& blockedPos : tilesBlockedAbsolute)
  1849. gen->setOccupied(blockedPos, ETileType::USED);
  1850. //check if boarding position is accessible
  1851. gen->foreach_neighbour(position, [this, &shipAccessCandidates](const int3 & v)
  1852. {
  1853. if(!gen->isBlocked(v) && gen->getZoneID(v)==id)
  1854. {
  1855. //make sure that it's possible to create path to boarding position
  1856. if(connectWithCenter(v, false, false))
  1857. shipAccessCandidates.insert(v);
  1858. }
  1859. });
  1860. //check if we can connect shipyard entrance with path
  1861. if(!connectWithCenter(candidateTile + shipyard->getVisitableOffset(), false))
  1862. shipAccessCandidates.clear();
  1863. //rollback temporary map
  1864. for(auto& blockedPos : tilesBlockedAbsolute)
  1865. gen->setOccupied(blockedPos, ETileType::POSSIBLE);
  1866. if(!shipAccessCandidates.empty() && isAccessibleFromSomewhere(shipyard->appearance, candidateTile))
  1867. {
  1868. targetTile = candidateTile;
  1869. break; //no need to check other offsets as we already found position
  1870. }
  1871. shipAccessCandidates.clear(); //invalidate positions
  1872. }
  1873. if(!targetTile.valid())
  1874. {
  1875. delete shipyard;
  1876. return false;
  1877. }
  1878. if(tryToPlaceObjectAndConnectToPath(shipyard, targetTile)==EObjectPlacingResult::SUCCESS)
  1879. {
  1880. placeObject(shipyard, targetTile);
  1881. guardObject(shipyard, guardStrength, false, true);
  1882. for(auto& accessPosition : shipAccessCandidates)
  1883. {
  1884. if(connectPath(accessPosition, false))
  1885. {
  1886. gen->setOccupied(accessPosition, ETileType::FREE);
  1887. return true;
  1888. }
  1889. }
  1890. }
  1891. logGlobal->warn("Cannot find path to shipyard boarding position");
  1892. delete shipyard;
  1893. return false;
  1894. }
  1895. void CRmgTemplateZone::createTreasures()
  1896. {
  1897. int mapMonsterStrength = gen->getMapGenOptions().getMonsterStrength();
  1898. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1899. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1900. minGuardedValue = minGuardedValues[monsterStrength];
  1901. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1902. {
  1903. return lhs.max > rhs.max;
  1904. };
  1905. //place biggest treasures first at large distance, place smaller ones inbetween
  1906. boost::sort(treasureInfo, valueComparator);
  1907. //sort treasures by ascending value so we can stop checking treasures with too high value
  1908. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  1909. {
  1910. return oi1.value < oi2.value;
  1911. });
  1912. int totalDensity = 0;
  1913. for (auto t : treasureInfo)
  1914. {
  1915. //discard objects with too high value to be ever placed
  1916. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  1917. {
  1918. return oi.value > t.max;
  1919. });
  1920. totalDensity += t.density;
  1921. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1922. //also, normalize it to zone count - higher count means relatively smaller zones
  1923. //this is squared distance for optimization purposes
  1924. const float minDistance = std::max<float>((125.f / totalDensity), 2.0f);
  1925. //distance lower than 2 causes objects to overlap and crash
  1926. bool stop = false;
  1927. do {
  1928. //optimization - don't check tiles which are not allowed
  1929. vstd::erase_if(possibleTiles, [this](const int3 &tile) -> bool
  1930. {
  1931. //for water area we sholdn't place treasures close to coast
  1932. for(auto & lake : lakes)
  1933. if(vstd::contains(lake.distance, tile) && lake.distance[tile] < 2)
  1934. return true;
  1935. return !gen->isPossible(tile) || gen->getZoneID(tile)!=getId();
  1936. });
  1937. int3 treasureTilePos;
  1938. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1939. do
  1940. {
  1941. if (!findPlaceForTreasurePile(minDistance, treasureTilePos, t.min))
  1942. {
  1943. stop = true;
  1944. break;
  1945. }
  1946. }
  1947. while (!createTreasurePile(treasureTilePos, minDistance, t)); //failed creation - position was wrong, cannot connect it
  1948. } while (!stop);
  1949. }
  1950. }
  1951. void CRmgTemplateZone::createObstacles1()
  1952. {
  1953. if (pos.z) //underground
  1954. {
  1955. //now make sure all accessible tiles have no additional rock on them
  1956. std::vector<int3> accessibleTiles;
  1957. for (auto tile : tileinfo)
  1958. {
  1959. if (gen->isFree(tile) || gen->isUsed(tile))
  1960. {
  1961. accessibleTiles.push_back(tile);
  1962. }
  1963. }
  1964. gen->getEditManager()->getTerrainSelection().setSelection(accessibleTiles);
  1965. gen->getEditManager()->drawTerrain(terrainType, &gen->rand);
  1966. }
  1967. }
  1968. void CRmgTemplateZone::createObstacles2()
  1969. {
  1970. typedef std::vector<ObjectTemplate> obstacleVector;
  1971. //obstacleVector possibleObstacles;
  1972. std::map <ui8, obstacleVector> obstaclesBySize;
  1973. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1974. std::vector<obstaclePair> possibleObstacles;
  1975. //get all possible obstacles for this terrain
  1976. for (auto primaryID : VLC->objtypeh->knownObjects())
  1977. {
  1978. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1979. {
  1980. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1981. if (handler->isStaticObject())
  1982. {
  1983. for (auto temp : handler->getTemplates())
  1984. {
  1985. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1986. obstaclesBySize[(ui8)temp.getBlockedOffsets().size()].push_back(temp);
  1987. }
  1988. }
  1989. }
  1990. }
  1991. for (auto o : obstaclesBySize)
  1992. {
  1993. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1994. }
  1995. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1996. {
  1997. return p1.first > p2.first; //bigger obstacles first
  1998. });
  1999. auto sel = gen->getEditManager()->getTerrainSelection();
  2000. sel.clearSelection();
  2001. auto tryToPlaceObstacleHere = [this, &possibleObstacles](int3& tile, int index)-> bool
  2002. {
  2003. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  2004. int3 obstaclePos = tile + temp.getBlockMapOffset();
  2005. if (canObstacleBePlacedHere(temp, obstaclePos)) //can be placed here
  2006. {
  2007. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  2008. placeObject(obj, obstaclePos, false);
  2009. return true;
  2010. }
  2011. return false;
  2012. };
  2013. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  2014. for (auto tile : boost::adaptors::reverse(tileinfo))
  2015. {
  2016. //fill tiles that should be blocked with obstacles
  2017. if (gen->shouldBeBlocked(tile))
  2018. {
  2019. //start from biggets obstacles
  2020. for (int i = 0; i < possibleObstacles.size(); i++)
  2021. {
  2022. if (tryToPlaceObstacleHere(tile, i))
  2023. break;
  2024. }
  2025. }
  2026. }
  2027. //cleanup - remove unused possible tiles to make space for roads
  2028. for (auto tile : tileinfo)
  2029. {
  2030. if (gen->isPossible(tile))
  2031. {
  2032. gen->setOccupied (tile, ETileType::FREE);
  2033. }
  2034. }
  2035. }
  2036. void CRmgTemplateZone::connectRoads()
  2037. {
  2038. logGlobal->debug("Started building roads");
  2039. std::set<int3> roadNodesCopy(roadNodes);
  2040. std::set<int3> processed;
  2041. while(!roadNodesCopy.empty())
  2042. {
  2043. int3 node = *roadNodesCopy.begin();
  2044. roadNodesCopy.erase(node);
  2045. int3 cross(-1, -1, -1);
  2046. auto comparator = [=](int3 lhs, int3 rhs) { return node.dist2dSQ(lhs) < node.dist2dSQ(rhs); };
  2047. if (processed.size()) //connect with already existing network
  2048. {
  2049. cross = *boost::range::min_element(processed, comparator); //find another remaining node
  2050. }
  2051. else if (roadNodesCopy.size()) //connect with any other unconnected node
  2052. {
  2053. cross = *boost::range::min_element(roadNodesCopy, comparator); //find another remaining node
  2054. }
  2055. else //no other nodes left, for example single road node in this zone
  2056. break;
  2057. logGlobal->debug("Building road from %s to %s", node.toString(), cross.toString());
  2058. if (createRoad(node, cross))
  2059. {
  2060. processed.insert(cross); //don't draw road starting at end point which is already connected
  2061. vstd::erase_if_present(roadNodesCopy, cross);
  2062. }
  2063. processed.insert(node);
  2064. }
  2065. drawRoads();
  2066. logGlobal->debug("Finished building roads");
  2067. }
  2068. void CRmgTemplateZone::drawRoads()
  2069. {
  2070. std::vector<int3> tiles;
  2071. for (auto tile : roads)
  2072. {
  2073. if(gen->map->isInTheMap(tile))
  2074. tiles.push_back (tile);
  2075. }
  2076. for (auto tile : roadNodes)
  2077. {
  2078. if (gen->getZoneID(tile) == id) //mark roads for our nodes, but not for zone guards in other zones
  2079. tiles.push_back(tile);
  2080. }
  2081. gen->getEditManager()->getTerrainSelection().setSelection(tiles);
  2082. gen->getEditManager()->drawRoad(gen->getConfig().defaultRoadType, &gen->rand);
  2083. }
  2084. bool CRmgTemplateZone::fill()
  2085. {
  2086. initTerrainType();
  2087. addAllPossibleObjects();
  2088. //zone center should be always clear to allow other tiles to connect
  2089. initFreeTiles();
  2090. connectLater(); //ideally this should work after fractalize, but fails
  2091. fractalize();
  2092. placeMines();
  2093. createRequiredObjects();
  2094. createTreasures();
  2095. logGlobal->info("Zone %d filled successfully", id);
  2096. return true;
  2097. }
  2098. bool CRmgTemplateZone::findPlaceForTreasurePile(float min_dist, int3 &pos, int value)
  2099. {
  2100. float best_distance = 0;
  2101. bool result = false;
  2102. bool needsGuard = isGuardNeededForTreasure(value);
  2103. //logGlobal->info("Min dist for density %f is %d", density, min_dist);
  2104. for(auto tile : possibleTiles)
  2105. {
  2106. auto dist = gen->getNearestObjectDistance(tile);
  2107. if ((dist >= min_dist) && (dist > best_distance))
  2108. {
  2109. bool allTilesAvailable = true;
  2110. gen->foreach_neighbour (tile, [this, &allTilesAvailable, needsGuard](int3 neighbour)
  2111. {
  2112. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || gen->getZoneID(neighbour)==getId() || (!needsGuard && gen->isFree(neighbour))))
  2113. {
  2114. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  2115. }
  2116. });
  2117. if (allTilesAvailable)
  2118. {
  2119. best_distance = dist;
  2120. pos = tile;
  2121. result = true;
  2122. }
  2123. }
  2124. }
  2125. if (result)
  2126. {
  2127. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  2128. }
  2129. return result;
  2130. }
  2131. bool CRmgTemplateZone::canObstacleBePlacedHere(ObjectTemplate &temp, int3 &pos)
  2132. {
  2133. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  2134. return false;
  2135. auto tilesBlockedByObject = temp.getBlockedOffsets();
  2136. for (auto blockingTile : tilesBlockedByObject)
  2137. {
  2138. int3 t = pos + blockingTile;
  2139. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)) || !temp.canBePlacedAt(gen->map->getTile(t).terType))
  2140. {
  2141. return false; //if at least one tile is not possible, object can't be placed here
  2142. }
  2143. }
  2144. return true;
  2145. }
  2146. bool CRmgTemplateZone::isAccessibleFromSomewhere(ObjectTemplate & appearance, const int3 & tile) const
  2147. {
  2148. return getAccessibleOffset(appearance, tile).valid();
  2149. }
  2150. int3 CRmgTemplateZone::getAccessibleOffset(ObjectTemplate & appearance, const int3 & tile) const
  2151. {
  2152. auto tilesBlockedByObject = appearance.getBlockedOffsets();
  2153. int3 ret(-1, -1, -1);
  2154. for (int x = -1; x < 2; x++)
  2155. {
  2156. for (int y = -1; y <2; y++)
  2157. {
  2158. if (x && y) //check only if object is visitable from another tile
  2159. {
  2160. int3 offset = int3(x, y, 0) - appearance.getVisitableOffset();
  2161. if (!vstd::contains(tilesBlockedByObject, offset))
  2162. {
  2163. int3 nearbyPos = tile + offset;
  2164. if (gen->map->isInTheMap(nearbyPos))
  2165. {
  2166. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos) && tileinfo.find(nearbyPos) != tileinfo.end())
  2167. ret = nearbyPos;
  2168. }
  2169. }
  2170. }
  2171. }
  2172. }
  2173. return ret;
  2174. }
  2175. void CRmgTemplateZone::setTemplateForObject(CGObjectInstance* obj)
  2176. {
  2177. if (obj->appearance.id == Obj::NO_OBJ)
  2178. {
  2179. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  2180. if (templates.empty())
  2181. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID % obj->subID % pos.toString()));
  2182. obj->appearance = templates.front();
  2183. }
  2184. }
  2185. bool CRmgTemplateZone::areAllTilesAvailable(CGObjectInstance* obj, int3& tile, const std::set<int3>& tilesBlockedByObject) const
  2186. {
  2187. for (auto blockingTile : tilesBlockedByObject)
  2188. {
  2189. int3 t = tile + blockingTile;
  2190. if (!gen->map->isInTheMap(t) || !gen->isPossible(t) || gen->getZoneID(t)!=getId())
  2191. {
  2192. //if at least one tile is not possible, object can't be placed here
  2193. return false;
  2194. }
  2195. }
  2196. return true;
  2197. }
  2198. bool CRmgTemplateZone::findPlaceForObject(CGObjectInstance* obj, si32 min_dist, int3 &pos)
  2199. {
  2200. //we need object apperance to deduce free tile
  2201. setTemplateForObject(obj);
  2202. int best_distance = 0;
  2203. bool result = false;
  2204. auto tilesBlockedByObject = obj->getBlockedOffsets();
  2205. for (auto tile : tileinfo)
  2206. {
  2207. //object must be accessible from at least one surounding tile
  2208. if (!isAccessibleFromSomewhere(obj->appearance, tile))
  2209. continue;
  2210. auto ti = gen->getTile(tile);
  2211. auto dist = ti.getNearestObjectDistance();
  2212. //avoid borders
  2213. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  2214. {
  2215. if (areAllTilesAvailable(obj, tile, tilesBlockedByObject))
  2216. {
  2217. best_distance = static_cast<int>(dist);
  2218. pos = tile;
  2219. result = true;
  2220. }
  2221. }
  2222. }
  2223. if (result)
  2224. {
  2225. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  2226. }
  2227. return result;
  2228. }
  2229. void CRmgTemplateZone::checkAndPlaceObject(CGObjectInstance* object, const int3 &pos)
  2230. {
  2231. if (!gen->map->isInTheMap(pos))
  2232. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos.toString()));
  2233. object->pos = pos;
  2234. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  2235. 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()));
  2236. for (auto tile : object->getBlockedPos())
  2237. {
  2238. if (!gen->map->isInTheMap(tile))
  2239. 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()));
  2240. }
  2241. if (object->appearance.id == Obj::NO_OBJ)
  2242. {
  2243. auto terrainType = gen->map->getTile(pos).terType;
  2244. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  2245. if (templates.empty())
  2246. 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));
  2247. object->appearance = templates.front();
  2248. }
  2249. gen->getEditManager()->insertObject(object);
  2250. }
  2251. void CRmgTemplateZone::placeObject(CGObjectInstance* object, const int3 &pos, bool updateDistance)
  2252. {
  2253. checkAndPlaceObject (object, pos);
  2254. auto points = object->getBlockedPos();
  2255. if (object->isVisitable())
  2256. points.insert(pos + object->getVisitableOffset());
  2257. points.insert(pos);
  2258. for(auto p : points)
  2259. {
  2260. if (gen->map->isInTheMap(p))
  2261. {
  2262. gen->setOccupied(p, ETileType::USED);
  2263. }
  2264. }
  2265. if (updateDistance)
  2266. updateDistances(pos);
  2267. switch (object->ID)
  2268. {
  2269. case Obj::TOWN:
  2270. case Obj::RANDOM_TOWN:
  2271. case Obj::MONOLITH_TWO_WAY:
  2272. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2273. case Obj::MONOLITH_ONE_WAY_EXIT:
  2274. case Obj::SUBTERRANEAN_GATE:
  2275. case Obj::SHIPYARD:
  2276. {
  2277. addRoadNode(object->visitablePos());
  2278. }
  2279. break;
  2280. default:
  2281. break;
  2282. }
  2283. }
  2284. void CRmgTemplateZone::updateDistances(const int3 & pos)
  2285. {
  2286. for (auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  2287. {
  2288. ui32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  2289. gen->setNearestObjectDistance(tile, std::min((float)d, gen->getNearestObjectDistance(tile)));
  2290. }
  2291. }
  2292. void CRmgTemplateZone::placeAndGuardObject(CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  2293. {
  2294. placeObject(object, pos);
  2295. guardObject(object, str, zoneGuard);
  2296. }
  2297. void CRmgTemplateZone::placeSubterraneanGate(int3 pos, si32 guardStrength)
  2298. {
  2299. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  2300. auto gate = factory->create(ObjectTemplate());
  2301. placeObject (gate, pos, true);
  2302. addToConnectLater (getAccessibleOffset (gate->appearance, pos)); //guard will be placed on accessibleOffset
  2303. guardObject (gate, guardStrength, true);
  2304. }
  2305. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (const CGObjectInstance* object)
  2306. {
  2307. //get all tiles from which this object can be accessed
  2308. int3 visitable = object->visitablePos();
  2309. std::vector<int3> tiles;
  2310. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  2311. gen->foreach_neighbour(visitable, [&](int3& pos)
  2312. {
  2313. if (gen->isPossible(pos) || gen->isFree(pos))
  2314. {
  2315. if (!vstd::contains(tilesBlockedByObject, pos))
  2316. {
  2317. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  2318. {
  2319. tiles.push_back(pos);
  2320. }
  2321. }
  2322. };
  2323. });
  2324. return tiles;
  2325. }
  2326. bool CRmgTemplateZone::isGuardNeededForTreasure(int value)
  2327. {
  2328. return getType() != ETemplateZoneType::WATER && value > minGuardedValue;
  2329. }
  2330. bool CRmgTemplateZone::guardObject(CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  2331. {
  2332. std::vector<int3> tiles = getAccessibleOffsets(object);
  2333. int3 guardTile(-1, -1, -1);
  2334. if (tiles.size())
  2335. {
  2336. //guardTile = tiles.front();
  2337. guardTile = getAccessibleOffset(object->appearance, object->pos);
  2338. logGlobal->trace("Guard object at %s", object->pos.toString());
  2339. }
  2340. else
  2341. {
  2342. logGlobal->error("Failed to guard object at %s", object->pos.toString());
  2343. return false;
  2344. }
  2345. if (addMonster (guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  2346. {
  2347. for (auto pos : tiles)
  2348. {
  2349. if (gen->isPossible(pos) && gen->getZoneID(pos) == id)
  2350. gen->setOccupied(pos, ETileType::BLOCKED);
  2351. }
  2352. gen->foreach_neighbour (guardTile, [&](int3& pos)
  2353. {
  2354. if (gen->isPossible(pos) && gen->getZoneID(pos) == id)
  2355. gen->setOccupied(pos, ETileType::FREE);
  2356. });
  2357. gen->setOccupied (guardTile, ETileType::USED);
  2358. }
  2359. else //allow no guard or other object in front of this object
  2360. {
  2361. for (auto tile : tiles)
  2362. if (gen->isPossible(tile))
  2363. gen->setOccupied(tile, ETileType::FREE);
  2364. }
  2365. return true;
  2366. }
  2367. ObjectInfo CRmgTemplateZone::getRandomObject(CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  2368. {
  2369. //int objectsVisitableFromBottom = 0; //for debug
  2370. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  2371. ui32 total = 0;
  2372. //calculate actual treasure value range based on remaining value
  2373. ui32 maxVal = desiredValue - currentValue;
  2374. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  2375. //roulette wheel
  2376. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  2377. {
  2378. if (oi.value > maxVal)
  2379. break; //this assumes values are sorted in ascending order
  2380. if (oi.value >= minValue && oi.maxPerZone > 0)
  2381. {
  2382. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  2383. int3 newVisitablePos = info.nextTreasurePos;
  2384. if (!oi.templ.isVisitableFromTop())
  2385. {
  2386. //objectsVisitableFromBottom++;
  2387. //there must be free tiles under object
  2388. auto blockedOffsets = oi.templ.getBlockedOffsets();
  2389. if (!isAccessibleFromSomewhere(oi.templ, newVisitablePos))
  2390. continue;
  2391. }
  2392. //NOTE: y coordinate grows downwards
  2393. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  2394. {
  2395. bool fitsHere = false;
  2396. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  2397. {
  2398. for (auto tile : info.visitableFromTopPositions)
  2399. {
  2400. int3 actualTile = tile + newVisitableOffset;
  2401. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  2402. {
  2403. fitsHere = true;
  2404. break;
  2405. }
  2406. }
  2407. for (auto tile : info.visitableFromBottomPositions)
  2408. {
  2409. int3 actualTile = tile + newVisitableOffset;
  2410. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  2411. {
  2412. fitsHere = true;
  2413. break;
  2414. }
  2415. }
  2416. }
  2417. else //if new object is not visitable from top, it must be accessible from below or side
  2418. {
  2419. for (auto tile : info.visitableFromTopPositions)
  2420. {
  2421. int3 actualTile = tile + newVisitableOffset;
  2422. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  2423. {
  2424. fitsHere = true;
  2425. break;
  2426. }
  2427. }
  2428. for (auto tile : info.visitableFromBottomPositions)
  2429. {
  2430. int3 actualTile = tile + newVisitableOffset;
  2431. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  2432. {
  2433. fitsHere = true;
  2434. break;
  2435. }
  2436. }
  2437. }
  2438. if (!fitsHere)
  2439. continue;
  2440. }
  2441. //now check blockmap, including our already reserved pile area
  2442. bool fitsBlockmap = true;
  2443. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  2444. blockedOffsets.insert (newVisitableOffset);
  2445. for (auto blockingTile : blockedOffsets)
  2446. {
  2447. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  2448. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  2449. {
  2450. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  2451. break;
  2452. }
  2453. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  2454. {
  2455. fitsBlockmap = false;
  2456. break;
  2457. }
  2458. }
  2459. if (!fitsBlockmap)
  2460. continue;
  2461. total += oi.probability;
  2462. thresholds.push_back (std::make_pair (total, &oi));
  2463. }
  2464. }
  2465. if(thresholds.empty())
  2466. {
  2467. ObjectInfo oi;
  2468. //Generate pandora Box with gold if the value is extremely high
  2469. if(minValue > gen->getConfig().treasureValueLimit) //we don't have object valuable enough
  2470. {
  2471. oi.generateObject = [minValue]() -> CGObjectInstance *
  2472. {
  2473. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2474. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2475. obj->resources[Res::GOLD] = minValue;
  2476. return obj;
  2477. };
  2478. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2479. oi.value = minValue;
  2480. oi.probability = 0;
  2481. }
  2482. else //generate empty object with 0 value if the value if we can't spawn anything
  2483. {
  2484. oi.generateObject = []() -> CGObjectInstance *
  2485. {
  2486. return nullptr;
  2487. };
  2488. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  2489. oi.value = 0; // this field is checked to determine no object
  2490. oi.probability = 0;
  2491. }
  2492. return oi;
  2493. }
  2494. else
  2495. {
  2496. int r = gen->rand.nextInt (1, total);
  2497. //binary search = fastest
  2498. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r,
  2499. [](const std::pair<ui32, ObjectInfo*> &rhs, const int lhs)->bool
  2500. {
  2501. return (int)rhs.first < lhs;
  2502. });
  2503. return *(it->second);
  2504. }
  2505. }
  2506. void CRmgTemplateZone::addAllPossibleObjects()
  2507. {
  2508. ObjectInfo oi;
  2509. int numZones = static_cast<int>(gen->getZones().size());
  2510. for (auto primaryID : VLC->objtypeh->knownObjects())
  2511. {
  2512. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  2513. {
  2514. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  2515. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  2516. {
  2517. for (auto temp : handler->getTemplates())
  2518. {
  2519. if (temp.canBePlacedAt(terrainType))
  2520. {
  2521. oi.generateObject = [temp]() -> CGObjectInstance *
  2522. {
  2523. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  2524. };
  2525. auto rmgInfo = handler->getRMGInfo();
  2526. oi.value = rmgInfo.value;
  2527. oi.probability = rmgInfo.rarity;
  2528. oi.templ = temp;
  2529. oi.maxPerZone = rmgInfo.zoneLimit;
  2530. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  2531. possibleObjects.push_back(oi);
  2532. }
  2533. }
  2534. }
  2535. }
  2536. }
  2537. if(type == ETemplateZoneType::WATER)
  2538. return;
  2539. //prisons
  2540. //levels 1, 5, 10, 20, 30
  2541. static int prisonsLevels = std::min(gen->getConfig().prisonExperience.size(), gen->getConfig().prisonValues.size());
  2542. for(int i = 0; i < prisonsLevels; i++)
  2543. {
  2544. oi.generateObject = [i, this]() -> CGObjectInstance *
  2545. {
  2546. std::vector<ui32> possibleHeroes;
  2547. for(int j = 0; j < gen->map->allowedHeroes.size(); j++)
  2548. {
  2549. if(gen->map->allowedHeroes[j])
  2550. possibleHeroes.push_back(j);
  2551. }
  2552. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  2553. auto factory = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0);
  2554. auto obj = (CGHeroInstance *) factory->create(ObjectTemplate());
  2555. obj->subID = hid; //will be initialized later
  2556. obj->exp = gen->getConfig().prisonExperience[i];
  2557. obj->setOwner(PlayerColor::NEUTRAL);
  2558. gen->map->allowedHeroes[hid] = false; //ban this hero
  2559. gen->decreasePrisonsRemaining();
  2560. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  2561. return obj;
  2562. };
  2563. oi.setTemplate(Obj::PRISON, 0, terrainType);
  2564. oi.value = gen->getConfig().prisonValues[i];
  2565. oi.probability = 30;
  2566. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  2567. possibleObjects.push_back(oi);
  2568. }
  2569. //all following objects are unlimited
  2570. oi.maxPerZone = std::numeric_limits<ui32>().max();
  2571. std::vector<CCreature *> creatures; //native creatures for this zone
  2572. for (auto cre : VLC->creh->objects)
  2573. {
  2574. if (!cre->special && cre->faction == townType)
  2575. {
  2576. creatures.push_back(cre);
  2577. }
  2578. }
  2579. //dwellings
  2580. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  2581. for(auto dwellingType : dwellingTypes)
  2582. {
  2583. auto subObjects = VLC->objtypeh->knownSubObjects(dwellingType);
  2584. if(dwellingType == Obj::CREATURE_GENERATOR1)
  2585. {
  2586. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  2587. static int elementalConfluxROE[] = {7, 13, 16, 47};
  2588. for(int i = 0; i < 4; i++)
  2589. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  2590. }
  2591. for(auto secondaryID : subObjects)
  2592. {
  2593. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  2594. auto creatures = dwellingHandler->getProducedCreatures();
  2595. if(creatures.empty())
  2596. continue;
  2597. auto cre = creatures.front();
  2598. if(cre->faction == townType)
  2599. {
  2600. float nativeZonesCount = static_cast<float>(gen->getZoneCount(cre->faction));
  2601. oi.value = static_cast<ui32>(cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2)));
  2602. oi.probability = 40;
  2603. for(auto tmplate : dwellingHandler->getTemplates())
  2604. {
  2605. if(tmplate.canBePlacedAt(terrainType))
  2606. {
  2607. oi.generateObject = [tmplate, secondaryID, dwellingType]() -> CGObjectInstance *
  2608. {
  2609. auto obj = VLC->objtypeh->getHandlerFor(dwellingType, secondaryID)->create(tmplate);
  2610. obj->tempOwner = PlayerColor::NEUTRAL;
  2611. return obj;
  2612. };
  2613. oi.templ = tmplate;
  2614. possibleObjects.push_back(oi);
  2615. }
  2616. }
  2617. }
  2618. }
  2619. }
  2620. for(int i = 0; i < gen->getConfig().scrollValues.size(); i++)
  2621. {
  2622. oi.generateObject = [i, this]() -> CGObjectInstance *
  2623. {
  2624. auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  2625. auto obj = (CGArtifact *) factory->create(ObjectTemplate());
  2626. std::vector<SpellID> out;
  2627. for (auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  2628. {
  2629. if (gen->isAllowedSpell(spell->id) && spell->level == i + 1)
  2630. {
  2631. out.push_back(spell->id);
  2632. }
  2633. }
  2634. auto a = CArtifactInstance::createScroll(*RandomGeneratorUtil::nextItem(out, gen->rand));
  2635. obj->storedArtifact = a;
  2636. return obj;
  2637. };
  2638. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  2639. oi.value = gen->getConfig().scrollValues[i];
  2640. oi.probability = 30;
  2641. possibleObjects.push_back(oi);
  2642. }
  2643. //pandora box with gold
  2644. for(int i = 1; i < 5; i++)
  2645. {
  2646. oi.generateObject = [i]() -> CGObjectInstance *
  2647. {
  2648. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2649. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2650. obj->resources[Res::GOLD] = i * 5000;
  2651. return obj;
  2652. };
  2653. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2654. oi.value = i * gen->getConfig().pandoraMultiplierGold;
  2655. oi.probability = 5;
  2656. possibleObjects.push_back(oi);
  2657. }
  2658. //pandora box with experience
  2659. for (int i = 1; i < 5; i++)
  2660. {
  2661. oi.generateObject = [i]() -> CGObjectInstance *
  2662. {
  2663. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2664. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2665. obj->gainedExp = i * 5000;
  2666. return obj;
  2667. };
  2668. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2669. oi.value = i * gen->getConfig().pandoraMultiplierExperience;
  2670. oi.probability = 20;
  2671. possibleObjects.push_back(oi);
  2672. }
  2673. //pandora box with creatures
  2674. const std::vector<int> & tierValues = gen->getConfig().pandoraCreatureValues;
  2675. auto creatureToCount = [&tierValues](CCreature * creature) -> int
  2676. {
  2677. if (!creature->AIValue) //bug #2681
  2678. return 0; //this box won't be generated
  2679. int actualTier = creature->level > tierValues.size() ?
  2680. tierValues.size() - 1 :
  2681. creature->level - 1;
  2682. float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
  2683. if (creaturesAmount <= 5)
  2684. {
  2685. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  2686. if (creaturesAmount < 1)
  2687. return 0;
  2688. }
  2689. else if (creaturesAmount <= 12)
  2690. {
  2691. (creaturesAmount /= 2) *= 2;
  2692. }
  2693. else if (creaturesAmount <= 50)
  2694. {
  2695. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  2696. }
  2697. else
  2698. {
  2699. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  2700. }
  2701. return static_cast<int>(creaturesAmount);
  2702. };
  2703. for (auto creature : creatures)
  2704. {
  2705. int creaturesAmount = creatureToCount(creature);
  2706. if (!creaturesAmount)
  2707. continue;
  2708. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  2709. {
  2710. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2711. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2712. auto stack = new CStackInstance(creature, creaturesAmount);
  2713. obj->creatures.putStack(SlotID(0), stack);
  2714. return obj;
  2715. };
  2716. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2717. oi.value = static_cast<ui32>((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3);
  2718. oi.probability = 3;
  2719. possibleObjects.push_back(oi);
  2720. }
  2721. //Pandora with 12 spells of certain level
  2722. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  2723. {
  2724. oi.generateObject = [i, this]() -> CGObjectInstance *
  2725. {
  2726. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2727. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2728. std::vector <CSpell *> spells;
  2729. for (auto spell : VLC->spellh->objects)
  2730. {
  2731. if (gen->isAllowedSpell(spell->id) && spell->level == i)
  2732. spells.push_back(spell);
  2733. }
  2734. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2735. for (int j = 0; j < std::min(12, (int)spells.size()); j++)
  2736. {
  2737. obj->spells.push_back(spells[j]->id);
  2738. }
  2739. return obj;
  2740. };
  2741. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2742. oi.value = (i + 1) * gen->getConfig().pandoraMultiplierSpells; //5000 - 15000
  2743. oi.probability = 2;
  2744. possibleObjects.push_back(oi);
  2745. }
  2746. //Pandora with 15 spells of certain school
  2747. for (int i = 0; i < 4; i++)
  2748. {
  2749. oi.generateObject = [i, this]() -> CGObjectInstance *
  2750. {
  2751. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2752. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2753. std::vector <CSpell *> spells;
  2754. for (auto spell : VLC->spellh->objects)
  2755. {
  2756. if (gen->isAllowedSpell(spell->id) && spell->school[(ESpellSchool)i])
  2757. spells.push_back(spell);
  2758. }
  2759. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2760. for (int j = 0; j < std::min(15, (int)spells.size()); j++)
  2761. {
  2762. obj->spells.push_back(spells[j]->id);
  2763. }
  2764. return obj;
  2765. };
  2766. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2767. oi.value = gen->getConfig().pandoraSpellSchool;
  2768. oi.probability = 2;
  2769. possibleObjects.push_back(oi);
  2770. }
  2771. // Pandora box with 60 random spells
  2772. oi.generateObject = [this]() -> CGObjectInstance *
  2773. {
  2774. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  2775. auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
  2776. std::vector <CSpell *> spells;
  2777. for (auto spell : VLC->spellh->objects)
  2778. {
  2779. if (gen->isAllowedSpell(spell->id))
  2780. spells.push_back(spell);
  2781. }
  2782. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2783. for (int j = 0; j < std::min(60, (int)spells.size()); j++)
  2784. {
  2785. obj->spells.push_back(spells[j]->id);
  2786. }
  2787. return obj;
  2788. };
  2789. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2790. oi.value = gen->getConfig().pandoraSpell60;
  2791. oi.probability = 2;
  2792. possibleObjects.push_back(oi);
  2793. //seer huts with creatures or generic rewards
  2794. if(questArtZone.lock()) //we won't be placing seer huts if there is no zone left to place arties
  2795. {
  2796. static const int genericSeerHuts = 8;
  2797. int seerHutsPerType = 0;
  2798. const int questArtsRemaining = static_cast<int>(gen->getQuestArtsRemaning().size());
  2799. //general issue is that not many artifact types are available for quests
  2800. if (questArtsRemaining >= genericSeerHuts + (int)creatures.size())
  2801. {
  2802. seerHutsPerType = questArtsRemaining / (genericSeerHuts + (int)creatures.size());
  2803. }
  2804. else if (questArtsRemaining >= genericSeerHuts)
  2805. {
  2806. seerHutsPerType = 1;
  2807. }
  2808. oi.maxPerZone = seerHutsPerType;
  2809. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  2810. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  2811. {
  2812. ObjectInfo artInfo;
  2813. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  2814. artInfo.maxPerZone = 1;
  2815. artInfo.value = 2000; //treasure art
  2816. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  2817. artInfo.generateObject = [id]() -> CGObjectInstance *
  2818. {
  2819. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  2820. return handler->create(handler->getTemplates().front());
  2821. };
  2822. return artInfo;
  2823. };
  2824. for(int i = 0; i < std::min((int)creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  2825. {
  2826. auto creature = creatures[i];
  2827. int creaturesAmount = creatureToCount(creature);
  2828. if (!creaturesAmount)
  2829. continue;
  2830. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2831. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  2832. {
  2833. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  2834. auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
  2835. obj->rewardType = CGSeerHut::CREATURE;
  2836. obj->rID = creature->idNumber;
  2837. obj->rVal = creaturesAmount;
  2838. obj->quest->missionType = CQuest::MISSION_ART;
  2839. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2840. obj->quest->m5arts.push_back(artid);
  2841. obj->quest->lastDay = -1;
  2842. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2843. gen->banQuestArt(artid);
  2844. this->questArtZone.lock()->possibleObjects.push_back (generateArtInfo(artid));
  2845. return obj;
  2846. };
  2847. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2848. oi.value = static_cast<ui32>(((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3);
  2849. oi.probability = 3;
  2850. possibleObjects.push_back(oi);
  2851. }
  2852. static int seerLevels = std::min(gen->getConfig().questValues.size(), gen->getConfig().questRewardValues.size());
  2853. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  2854. {
  2855. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2856. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2857. oi.value = gen->getConfig().questValues[i];
  2858. oi.probability = 10;
  2859. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  2860. {
  2861. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  2862. auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
  2863. obj->rewardType = CGSeerHut::EXPERIENCE;
  2864. obj->rID = 0; //unitialized?
  2865. obj->rVal = gen->getConfig().questRewardValues[i];
  2866. obj->quest->missionType = CQuest::MISSION_ART;
  2867. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2868. obj->quest->m5arts.push_back(artid);
  2869. obj->quest->lastDay = -1;
  2870. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2871. gen->banQuestArt(artid);
  2872. this->questArtZone.lock()->possibleObjects.push_back(generateArtInfo(artid));
  2873. return obj;
  2874. };
  2875. possibleObjects.push_back(oi);
  2876. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  2877. {
  2878. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  2879. auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
  2880. obj->rewardType = CGSeerHut::RESOURCES;
  2881. obj->rID = Res::GOLD;
  2882. obj->rVal = gen->getConfig().questRewardValues[i];
  2883. obj->quest->missionType = CQuest::MISSION_ART;
  2884. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2885. obj->quest->m5arts.push_back(artid);
  2886. obj->quest->lastDay = -1;
  2887. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2888. gen->banQuestArt(artid);
  2889. this->questArtZone.lock()->possibleObjects.push_back(generateArtInfo(artid));
  2890. return obj;
  2891. };
  2892. possibleObjects.push_back(oi);
  2893. }
  2894. }
  2895. }
  2896. ObjectInfo::ObjectInfo()
  2897. : templ(), value(0), probability(0), maxPerZone(1)
  2898. {
  2899. }
  2900. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2901. {
  2902. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  2903. if(!templHandler)
  2904. return;
  2905. auto templates = templHandler->getTemplates(terrainType);
  2906. if(templates.empty())
  2907. return;
  2908. templ = templates.front();
  2909. }