CRmgTemplateZone.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  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. if (townTypes.size())
  914. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  915. else
  916. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  917. }
  918. }
  919. else //no player
  920. {
  921. if (townTypes.size())
  922. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  923. else
  924. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  925. }
  926. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  927. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  928. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  929. {
  930. //25% chance for neutral
  931. if (gen->rand.nextInt(1, 100) <= 25)
  932. {
  933. townType = ETownType::NEUTRAL;
  934. }
  935. else
  936. {
  937. if (townTypes.size())
  938. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  939. else if (monsterTypes.size())
  940. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  941. }
  942. }
  943. }
  944. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  945. {
  946. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  947. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  948. else
  949. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  950. //TODO: allow new types of terrain?
  951. if (pos.z)
  952. {
  953. if (terrainType != ETerrainType::LAVA)
  954. terrainType = ETerrainType::SUBTERRANEAN;
  955. }
  956. else
  957. {
  958. if (terrainType == ETerrainType::SUBTERRANEAN)
  959. terrainType = ETerrainType::DIRT;
  960. }
  961. paintZoneTerrain (gen, terrainType);
  962. }
  963. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  964. {
  965. std::vector<int3> tiles;
  966. for (auto tile : tileinfo)
  967. {
  968. tiles.push_back (tile);
  969. }
  970. gen->editManager->getTerrainSelection().setSelection(tiles);
  971. gen->editManager->drawTerrain(terrainType, &gen->rand);
  972. }
  973. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  974. {
  975. std::vector<Res::ERes> required_mines;
  976. required_mines.push_back(Res::ERes::WOOD);
  977. required_mines.push_back(Res::ERes::ORE);
  978. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  979. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  980. //TODO: factory / copy constructor?
  981. for (const auto & res : woodOre)
  982. {
  983. //TODO: these 2 should be close to town (within 12 tiles radius)
  984. for (int i = 0; i < mines[res]; i++)
  985. {
  986. auto mine = new CGMine();
  987. mine->ID = Obj::MINE;
  988. mine->subID = static_cast<si32>(res);
  989. mine->producedResource = res;
  990. mine->producedQuantity = mine->defaultResProduction();
  991. addRequiredObject(mine, 1500);
  992. }
  993. }
  994. for (const auto & res : preciousResources)
  995. {
  996. for (int i = 0; i < mines[res]; i++)
  997. {
  998. auto mine = new CGMine();
  999. mine->ID = Obj::MINE;
  1000. mine->subID = static_cast<si32>(res);
  1001. mine->producedResource = res;
  1002. mine->producedQuantity = mine->defaultResProduction();
  1003. addRequiredObject(mine, 3500);
  1004. }
  1005. }
  1006. for (int i = 0; i < mines[Res::GOLD]; i++)
  1007. {
  1008. auto mine = new CGMine();
  1009. mine->ID = Obj::MINE;
  1010. mine->subID = static_cast<si32>(Res::GOLD);
  1011. mine->producedResource = Res::GOLD;
  1012. mine->producedQuantity = mine->defaultResProduction();
  1013. addRequiredObject(mine, 7000);
  1014. }
  1015. return true;
  1016. }
  1017. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1018. {
  1019. logGlobal->traceStream() << "Creating required objects";
  1020. for(const auto &obj : requiredObjects)
  1021. {
  1022. int3 pos;
  1023. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  1024. {
  1025. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  1026. //TODO CLEANUP!
  1027. return false;
  1028. }
  1029. placeObject (gen, obj.first, pos);
  1030. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1031. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1032. }
  1033. return true;
  1034. }
  1035. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1036. {
  1037. //treasure density is proportional to map siz,e but must be scaled bakc to map size
  1038. //also, normalize it to zone count - higher count means relative smaller zones
  1039. //this is squared distance for optimization purposes
  1040. const double minDistance = std::max<float>((600.f * size * size * gen->getZones().size()) /
  1041. (gen->mapGenOptions->getWidth() * gen->mapGenOptions->getHeight() * totalDensity * (gen->map->twoLevel ? 2 : 1)), 2);
  1042. //distance lower than 2 causes objects to overlap and crash
  1043. do {
  1044. //optimization - don't check tiles which are not allowed
  1045. vstd::erase_if (possibleTiles, [gen](const int3 &tile) -> bool
  1046. {
  1047. return !gen->isPossible(tile);
  1048. });
  1049. int3 pos;
  1050. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  1051. {
  1052. break;
  1053. }
  1054. createTreasurePile (gen, pos, minDistance);
  1055. } while(true);
  1056. }
  1057. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1058. {
  1059. //tighten obstacles to improve visuals
  1060. for (int i = 0; i < 3; ++i)
  1061. {
  1062. int blockedTiles = 0;
  1063. int freeTiles = 0;
  1064. for (auto tile : tileinfo)
  1065. {
  1066. if (!gen->isPossible(tile)) //only possible tiles can change
  1067. continue;
  1068. int blockedNeighbours = 0;
  1069. int freeNeighbours = 0;
  1070. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1071. {
  1072. if (gen->isBlocked(pos))
  1073. blockedNeighbours++;
  1074. if (gen->isFree(pos))
  1075. freeNeighbours++;
  1076. });
  1077. if (blockedNeighbours > 4)
  1078. {
  1079. gen->setOccupied(tile, ETileType::BLOCKED);
  1080. blockedTiles++;
  1081. }
  1082. else if (freeNeighbours > 4)
  1083. {
  1084. gen->setOccupied(tile, ETileType::FREE);
  1085. freeTiles++;
  1086. }
  1087. }
  1088. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1089. }
  1090. #define MAKE_COOL_UNDERGROUND_TUNNELS false
  1091. if (pos.z && MAKE_COOL_UNDERGROUND_TUNNELS) //underground
  1092. {
  1093. std::vector<int3> rockTiles;
  1094. for (auto tile : tileinfo)
  1095. {
  1096. if (gen->shouldBeBlocked(tile))
  1097. {
  1098. bool placeRock = true;
  1099. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1100. {
  1101. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1102. placeRock = false;
  1103. });
  1104. if (placeRock)
  1105. {
  1106. rockTiles.push_back(tile);
  1107. }
  1108. }
  1109. }
  1110. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1111. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1112. for (auto tile : rockTiles)
  1113. {
  1114. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1115. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1116. //{
  1117. // if (!gen->isUsed(pos))
  1118. // gen->setOccupied (pos, ETileType::BLOCKED);
  1119. //});
  1120. }
  1121. }
  1122. typedef std::vector<ObjectTemplate> obstacleVector;
  1123. //obstacleVector possibleObstacles;
  1124. std::map <ui8, obstacleVector> obstaclesBySize;
  1125. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1126. std::vector<obstaclePair> possibleObstacles;
  1127. //get all possible obstacles for this terrain
  1128. for (auto primaryID : VLC->objtypeh->knownObjects())
  1129. {
  1130. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1131. {
  1132. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1133. if (handler->isStaticObject())
  1134. {
  1135. for (auto temp : handler->getTemplates())
  1136. {
  1137. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1138. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. for (auto o : obstaclesBySize)
  1144. {
  1145. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1146. }
  1147. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1148. {
  1149. return p1.first > p2.first; //bigger obstacles first
  1150. });
  1151. auto sel = gen->editManager->getTerrainSelection();
  1152. sel.clearSelection();
  1153. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1154. {
  1155. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1156. int3 obstaclePos = tile - temp.getBlockMapOffset();
  1157. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1158. {
  1159. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1160. placeObject(gen, obj, obstaclePos, false);
  1161. return true;
  1162. }
  1163. return false;
  1164. };
  1165. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1166. for (auto tile : boost::adaptors::reverse(tileinfo))
  1167. {
  1168. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1169. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1170. {
  1171. //start from biggets obstacles
  1172. for (int i = 0; i < possibleObstacles.size(); i++)
  1173. {
  1174. if (tryToPlaceObstacleHere(tile, i))
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. }
  1180. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1181. {
  1182. initTerrainType(gen);
  1183. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1184. addAllPossibleObjects (gen);
  1185. placeMines(gen);
  1186. createRequiredObjects(gen);
  1187. fractalize(gen); //after required objects are created and linked with their own paths
  1188. createTreasures(gen);
  1189. createObstacles(gen);
  1190. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1191. return true;
  1192. }
  1193. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos)
  1194. {
  1195. //si32 min_dist = sqrt(tileinfo.size()/density);
  1196. float best_distance = 0;
  1197. bool result = false;
  1198. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1199. for(auto tile : possibleTiles)
  1200. {
  1201. auto dist = gen->getNearestObjectDistance(tile);
  1202. if ((dist >= min_dist) && (dist > best_distance))
  1203. {
  1204. bool allTilesAvailable = true;
  1205. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  1206. {
  1207. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour)))
  1208. {
  1209. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1210. }
  1211. });
  1212. if (allTilesAvailable)
  1213. {
  1214. best_distance = dist;
  1215. pos = tile;
  1216. result = true;
  1217. }
  1218. }
  1219. }
  1220. if (result)
  1221. {
  1222. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1223. }
  1224. return result;
  1225. }
  1226. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1227. {
  1228. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1229. return false;
  1230. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1231. for (auto blockingTile : tilesBlockedByObject)
  1232. {
  1233. int3 t = pos + blockingTile;
  1234. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1235. {
  1236. return false; //if at least one tile is not possible, object can't be placed here
  1237. }
  1238. }
  1239. return true;
  1240. }
  1241. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1242. {
  1243. bool accessible = false;
  1244. for (int x = -1; x < 2; x++)
  1245. {
  1246. for (int y = -1; y <2; y++)
  1247. {
  1248. if (x && y) //check only if object is visitable from another tile
  1249. {
  1250. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1251. if (!vstd::contains(tilesBlockedByObject, offset))
  1252. {
  1253. int3 nearbyPos = tile + offset;
  1254. if (gen->map->isInTheMap(nearbyPos))
  1255. {
  1256. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1257. accessible = true;
  1258. }
  1259. }
  1260. }
  1261. };
  1262. }
  1263. return accessible;
  1264. }
  1265. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1266. {
  1267. //we need object apperance to deduce free tiles
  1268. if (obj->appearance.id == Obj::NO_OBJ)
  1269. {
  1270. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1271. if (templates.empty())
  1272. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1273. obj->appearance = templates.front();
  1274. }
  1275. //si32 min_dist = sqrt(tileinfo.size()/density);
  1276. int best_distance = 0;
  1277. bool result = false;
  1278. //si32 w = gen->map->width;
  1279. //si32 h = gen->map->height;
  1280. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1281. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1282. for (auto tile : tileinfo)
  1283. {
  1284. //object must be accessible from at least one surounding tile
  1285. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1286. continue;
  1287. auto ti = gen->getTile(tile);
  1288. auto dist = ti.getNearestObjectDistance();
  1289. //avoid borders
  1290. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1291. {
  1292. bool allTilesAvailable = true;
  1293. for (auto blockingTile : tilesBlockedByObject)
  1294. {
  1295. int3 t = tile + blockingTile;
  1296. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1297. {
  1298. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1299. break;
  1300. }
  1301. }
  1302. if (allTilesAvailable)
  1303. {
  1304. best_distance = dist;
  1305. pos = tile;
  1306. result = true;
  1307. }
  1308. }
  1309. }
  1310. if (result)
  1311. {
  1312. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1313. }
  1314. return result;
  1315. }
  1316. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1317. {
  1318. if (!gen->map->isInTheMap(pos))
  1319. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1320. object->pos = pos;
  1321. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1322. 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()));
  1323. for (auto tile : object->getBlockedPos())
  1324. {
  1325. if (!gen->map->isInTheMap(tile))
  1326. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1327. }
  1328. if (object->appearance.id == Obj::NO_OBJ)
  1329. {
  1330. auto terrainType = gen->map->getTile(pos).terType;
  1331. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1332. if (templates.empty())
  1333. 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));
  1334. object->appearance = templates.front();
  1335. }
  1336. gen->editManager->insertObject(object, pos);
  1337. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1338. }
  1339. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1340. {
  1341. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1342. checkAndPlaceObject (gen, object, pos);
  1343. auto points = object->getBlockedPos();
  1344. if (object->isVisitable())
  1345. points.insert(pos + object->getVisitableOffset());
  1346. points.insert(pos);
  1347. for(auto p : points)
  1348. {
  1349. if (gen->map->isInTheMap(p))
  1350. {
  1351. gen->setOccupied(p, ETileType::USED);
  1352. }
  1353. }
  1354. if (updateDistance)
  1355. {
  1356. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1357. {
  1358. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1359. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1360. }
  1361. }
  1362. }
  1363. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1364. {
  1365. placeObject(gen, object, pos);
  1366. guardObject(gen, object, str, zoneGuard);
  1367. }
  1368. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1369. {
  1370. //get all tiles from which this object can be accessed
  1371. int3 visitable = object->visitablePos();
  1372. std::vector<int3> tiles;
  1373. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1374. gen->foreach_neighbour(visitable, [&](int3& pos)
  1375. {
  1376. if (gen->isPossible(pos))
  1377. {
  1378. if (!vstd::contains(tilesBlockedByObject, pos))
  1379. {
  1380. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1381. {
  1382. tiles.push_back(pos);
  1383. }
  1384. }
  1385. };
  1386. });
  1387. return tiles;
  1388. }
  1389. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1390. {
  1391. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1392. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1393. int3 guardTile(-1,-1,-1);
  1394. for (auto tile : tiles)
  1395. {
  1396. //crunching path may fail if center of the zone is directly over wide object
  1397. //make sure object is accessible before surrounding it with blocked tiles
  1398. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1399. {
  1400. guardTile = tile;
  1401. break;
  1402. }
  1403. }
  1404. if (!guardTile.valid())
  1405. {
  1406. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1407. return false;
  1408. }
  1409. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1410. {
  1411. for (auto pos : tiles)
  1412. {
  1413. if (!gen->isFree(pos))
  1414. gen->setOccupied(pos, ETileType::BLOCKED);
  1415. }
  1416. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1417. {
  1418. if (gen->isPossible(pos))
  1419. gen->setOccupied (pos, ETileType::FREE);
  1420. });
  1421. gen->setOccupied (guardTile, ETileType::USED);
  1422. }
  1423. else //allow no guard or other object in front of this object
  1424. {
  1425. for (auto tile : tiles)
  1426. if (gen->isPossible(tile))
  1427. gen->setOccupied (tile, ETileType::FREE);
  1428. }
  1429. return true;
  1430. }
  1431. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1432. {
  1433. //int objectsVisitableFromBottom = 0; //for debug
  1434. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1435. ui32 total = 0;
  1436. //calculate actual treasure value range based on remaining value
  1437. ui32 maxVal = maxValue - currentValue;
  1438. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1439. //roulette wheel
  1440. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1441. {
  1442. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1443. {
  1444. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1445. int3 newVisitablePos = info.nextTreasurePos;
  1446. if (!oi.templ.isVisitableFromTop())
  1447. {
  1448. //objectsVisitableFromBottom++;
  1449. //there must be free tiles under object
  1450. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1451. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1452. continue;
  1453. }
  1454. //NOTE: y coordinate grows downwards
  1455. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1456. {
  1457. bool fitsHere = false;
  1458. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1459. {
  1460. for (auto tile : info.visitableFromTopPositions)
  1461. {
  1462. int3 actualTile = tile + newVisitableOffset;
  1463. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1464. {
  1465. fitsHere = true;
  1466. break;
  1467. }
  1468. }
  1469. for (auto tile : info.visitableFromBottomPositions)
  1470. {
  1471. int3 actualTile = tile + newVisitableOffset;
  1472. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1473. {
  1474. fitsHere = true;
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. else //if new object is not visitable from top, it must be accessible from below or side
  1480. {
  1481. for (auto tile : info.visitableFromTopPositions)
  1482. {
  1483. int3 actualTile = tile + newVisitableOffset;
  1484. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1485. {
  1486. fitsHere = true;
  1487. break;
  1488. }
  1489. }
  1490. for (auto tile : info.visitableFromBottomPositions)
  1491. {
  1492. int3 actualTile = tile + newVisitableOffset;
  1493. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1494. {
  1495. fitsHere = true;
  1496. break;
  1497. }
  1498. }
  1499. }
  1500. if (!fitsHere)
  1501. continue;
  1502. }
  1503. //now check blockmap, including our already reserved pile area
  1504. bool fitsBlockmap = true;
  1505. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1506. blockedOffsets.insert (newVisitableOffset);
  1507. for (auto blockingTile : blockedOffsets)
  1508. {
  1509. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1510. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1511. {
  1512. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1513. break;
  1514. }
  1515. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1516. {
  1517. fitsBlockmap = false;
  1518. break;
  1519. }
  1520. }
  1521. if (!fitsBlockmap)
  1522. continue;
  1523. total += oi.probability;
  1524. //assert (oi.value > 0);
  1525. tresholds.push_back (std::make_pair (total, oi));
  1526. }
  1527. }
  1528. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1529. if (tresholds.empty())
  1530. {
  1531. ObjectInfo oi;
  1532. //Generate pandora Box with gold if the value is extremely high
  1533. if (minValue > 20000) //we don't have object valuable enough
  1534. {
  1535. oi.generateObject = [minValue]() -> CGObjectInstance *
  1536. {
  1537. auto obj = new CGPandoraBox();
  1538. obj->ID = Obj::PANDORAS_BOX;
  1539. obj->subID = 0;
  1540. obj->resources[Res::GOLD] = minValue;
  1541. return obj;
  1542. };
  1543. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1544. oi.value = minValue;
  1545. oi.probability = 0;
  1546. }
  1547. else //generate empty object with 0 value if the value if we can't spawn anything
  1548. {
  1549. oi.generateObject = [gen]() -> CGObjectInstance *
  1550. {
  1551. return nullptr;
  1552. };
  1553. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1554. oi.value = 0; // this field is checked to determine no object
  1555. oi.probability = 0;
  1556. }
  1557. return oi;
  1558. }
  1559. else
  1560. {
  1561. int r = gen->rand.nextInt (1, total);
  1562. for (auto t : tresholds)
  1563. {
  1564. if (r <= t.first)
  1565. return t.second;
  1566. }
  1567. assert (0); //we should never be here
  1568. }
  1569. //FIXME: control reaches end of non-void function. Missing return?
  1570. }
  1571. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1572. {
  1573. ObjectInfo oi;
  1574. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1575. int numZones = gen->getZones().size();
  1576. for (auto primaryID : VLC->objtypeh->knownObjects())
  1577. {
  1578. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1579. {
  1580. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1581. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1582. {
  1583. for (auto temp : handler->getTemplates())
  1584. {
  1585. if (temp.canBePlacedAt(terrainType))
  1586. {
  1587. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1588. {
  1589. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1590. };
  1591. auto rmgInfo = handler->getRMGInfo();
  1592. oi.value = rmgInfo.value;
  1593. oi.probability = rmgInfo.rarity;
  1594. oi.templ = temp;
  1595. oi.maxPerZone = rmgInfo.zoneLimit;
  1596. vstd::amin (oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1597. possibleObjects.push_back (oi);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. }
  1603. //prisons
  1604. //levels 1, 5, 10, 20, 30
  1605. static int prisonExp[] = {0, 5000, 15000, 90000, 500000};
  1606. static int prisonValues[] = {2500, 5000, 10000, 20000, 30000};
  1607. for (int i = 0; i < 5; i++)
  1608. {
  1609. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1610. {
  1611. auto obj = new CGHeroInstance;
  1612. obj->ID = Obj::PRISON;
  1613. std::vector<ui32> possibleHeroes;
  1614. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1615. {
  1616. if (gen->map->allowedHeroes[j])
  1617. possibleHeroes.push_back(j);
  1618. }
  1619. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1620. obj->subID = hid; //will be initialized later
  1621. obj->exp = prisonExp[i]; //game crashes at hero level up
  1622. //obj->exp = 0;
  1623. obj->setOwner(PlayerColor::NEUTRAL);
  1624. gen->map->allowedHeroes[hid] = false; //ban this hero
  1625. gen->decreasePrisonsRemaining();
  1626. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1627. return obj;
  1628. };
  1629. oi.setTemplate (Obj::PRISON, 0, terrainType);
  1630. oi.value = prisonValues[i];
  1631. oi.probability = 30;
  1632. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1633. possibleObjects.push_back (oi);
  1634. }
  1635. //all following objects are unlimited
  1636. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1637. //dwellings
  1638. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1639. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1640. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1641. for (int i = 0; i < 4; i++)
  1642. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1643. for (auto secondaryID : subObjects)
  1644. {
  1645. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1646. auto creatures = dwellingHandler->getProducedCreatures();
  1647. if (creatures.empty())
  1648. continue;
  1649. auto cre = creatures.front();
  1650. if (cre->faction == townType)
  1651. {
  1652. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1653. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1654. oi.probability = 40;
  1655. for (auto temp : dwellingHandler->getTemplates())
  1656. {
  1657. if (temp.canBePlacedAt(terrainType))
  1658. {
  1659. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1660. {
  1661. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1662. //dwellingHandler->configureObject(obj, gen->rand);
  1663. obj->tempOwner = PlayerColor::NEUTRAL;
  1664. return obj;
  1665. };
  1666. oi.templ = temp;
  1667. possibleObjects.push_back (oi);
  1668. }
  1669. }
  1670. }
  1671. }
  1672. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1673. for (int i = 0; i < 5; i++)
  1674. {
  1675. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1676. {
  1677. auto obj = new CGArtifact();
  1678. obj->ID = Obj::SPELL_SCROLL;
  1679. obj->subID = 0;
  1680. std::vector<SpellID> out;
  1681. //TODO: unify with cb->getAllowedSpells?
  1682. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1683. {
  1684. const CSpell *spell = SpellID(i).toSpell();
  1685. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1686. {
  1687. out.push_back(spell->id);
  1688. }
  1689. }
  1690. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1691. gen->map->addNewArtifactInstance(a);
  1692. obj->storedArtifact = a;
  1693. return obj;
  1694. };
  1695. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1696. oi.value = scrollValues[i];
  1697. oi.probability = 30;
  1698. possibleObjects.push_back (oi);
  1699. }
  1700. //pandora box with gold
  1701. for (int i = 1; i < 5; i++)
  1702. {
  1703. oi.generateObject = [i]() -> CGObjectInstance *
  1704. {
  1705. auto obj = new CGPandoraBox();
  1706. obj->ID = Obj::PANDORAS_BOX;
  1707. obj->subID = 0;
  1708. obj->resources[Res::GOLD] = i * 5000;
  1709. return obj;
  1710. };
  1711. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1712. oi.value = i * 5000;;
  1713. oi.probability = 5;
  1714. possibleObjects.push_back (oi);
  1715. }
  1716. //pandora box with experience
  1717. for (int i = 1; i < 5; i++)
  1718. {
  1719. oi.generateObject = [i]() -> CGObjectInstance *
  1720. {
  1721. auto obj = new CGPandoraBox();
  1722. obj->ID = Obj::PANDORAS_BOX;
  1723. obj->subID = 0;
  1724. obj->gainedExp = i * 5000;
  1725. return obj;
  1726. };
  1727. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1728. oi.value = i * 6000;;
  1729. oi.probability = 20;
  1730. possibleObjects.push_back (oi);
  1731. }
  1732. //pandora box with creatures
  1733. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1734. for (auto creature : VLC->creh->creatures)
  1735. {
  1736. if (!creature->special && creature->faction == townType)
  1737. {
  1738. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1739. float creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1740. if (creaturesAmount <= 5)
  1741. {
  1742. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1743. if (creaturesAmount < 1)
  1744. continue;
  1745. }
  1746. else if (creaturesAmount <= 12)
  1747. {
  1748. (creaturesAmount /= 2) *= 2;
  1749. }
  1750. else if (creaturesAmount <= 50)
  1751. {
  1752. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1753. }
  1754. else
  1755. {
  1756. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1757. }
  1758. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1759. {
  1760. auto obj = new CGPandoraBox();
  1761. obj->ID = Obj::PANDORAS_BOX;
  1762. obj->subID = 0;
  1763. auto stack = new CStackInstance(creature, creaturesAmount);
  1764. obj->creatures.putStack(SlotID(0), stack);
  1765. return obj;
  1766. };
  1767. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1768. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1769. oi.probability = 3;
  1770. possibleObjects.push_back (oi);
  1771. }
  1772. }
  1773. //Pandora with 12 spells of certain level
  1774. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1775. {
  1776. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1777. {
  1778. auto obj = new CGPandoraBox();
  1779. obj->ID = Obj::PANDORAS_BOX;
  1780. obj->subID = 0;
  1781. std::vector <CSpell *> spells;
  1782. for (auto spell : VLC->spellh->objects)
  1783. {
  1784. if (!spell->isSpecialSpell() && spell->level == i)
  1785. spells.push_back(spell);
  1786. }
  1787. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1788. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1789. {
  1790. obj->spells.push_back (spells[j]->id);
  1791. }
  1792. return obj;
  1793. };
  1794. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1795. oi.value = (i + 1) * 2500; //5000 - 15000
  1796. oi.probability = 2;
  1797. possibleObjects.push_back (oi);
  1798. }
  1799. //Pandora with 15 spells of certain school
  1800. for (int i = 1; i <= 4; i++)
  1801. {
  1802. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1803. {
  1804. auto obj = new CGPandoraBox();
  1805. obj->ID = Obj::PANDORAS_BOX;
  1806. obj->subID = 0;
  1807. std::vector <CSpell *> spells;
  1808. for (auto spell : VLC->spellh->objects)
  1809. {
  1810. if (!spell->isSpecialSpell())
  1811. {
  1812. bool school = false; //TODO: we could have better interface for iterating schools
  1813. switch (i)
  1814. {
  1815. case 1:
  1816. school = spell->air;
  1817. break;
  1818. case 2:
  1819. school = spell->earth;
  1820. break;
  1821. case 3:
  1822. school = spell->fire;
  1823. break;
  1824. case 4:
  1825. school = spell->water;
  1826. break;
  1827. }
  1828. if (school)
  1829. spells.push_back(spell);
  1830. }
  1831. }
  1832. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1833. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1834. {
  1835. obj->spells.push_back (spells[j]->id);
  1836. }
  1837. return obj;
  1838. };
  1839. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1840. oi.value = 15000;
  1841. oi.probability = 2;
  1842. possibleObjects.push_back (oi);
  1843. }
  1844. // Pandora box with 60 random spells
  1845. oi.generateObject = [gen]() -> CGObjectInstance *
  1846. {
  1847. auto obj = new CGPandoraBox();
  1848. obj->ID = Obj::PANDORAS_BOX;
  1849. obj->subID = 0;
  1850. std::vector <CSpell *> spells;
  1851. for (auto spell : VLC->spellh->objects)
  1852. {
  1853. if (!spell->isSpecialSpell())
  1854. spells.push_back(spell);
  1855. }
  1856. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1857. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1858. {
  1859. obj->spells.push_back (spells[j]->id);
  1860. }
  1861. return obj;
  1862. };
  1863. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1864. oi.value = 3000;
  1865. oi.probability = 2;
  1866. possibleObjects.push_back (oi);
  1867. }
  1868. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1869. {
  1870. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1871. }