CRmgTemplateZone.cpp 79 KB

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