CRmgTemplateZone.cpp 59 KB

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