CRmgTemplateZone.cpp 71 KB

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