CRmgTemplateZone.cpp 81 KB

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