CRmgTemplateZone.cpp 66 KB

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