2
0

CRmgTemplateZone.cpp 54 KB

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