CRmgTemplateZone.cpp 57 KB

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