CRmgTemplateZone.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687
  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. bool CRmgTemplateZone::crunchPath(CMapGenerator* gen, const int3 &src, const int3 &dst, bool onlyStraight, std::set<int3>* clearedTiles)
  520. {
  521. /*
  522. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  523. do not leave zone border
  524. */
  525. bool result = false;
  526. bool end = false;
  527. int3 currentPos = src;
  528. float distance = currentPos.dist2dSQ (dst);
  529. while (!end)
  530. {
  531. if (currentPos == dst)
  532. {
  533. result = true;
  534. break;
  535. }
  536. auto lastDistance = distance;
  537. auto processNeighbours = [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  538. {
  539. if (!result) //not sure if lambda is worth it...
  540. {
  541. if (pos == dst)
  542. {
  543. result = true;
  544. end = true;
  545. }
  546. if (pos.dist2dSQ (dst) < distance)
  547. {
  548. if (!gen->isBlocked(pos))
  549. {
  550. if (vstd::contains (tileinfo, pos))
  551. {
  552. if (gen->isPossible(pos))
  553. {
  554. gen->setOccupied (pos, ETileType::FREE);
  555. if (clearedTiles)
  556. clearedTiles->insert(pos);
  557. currentPos = pos;
  558. distance = currentPos.dist2dSQ (dst);
  559. }
  560. else if (gen->isFree(pos))
  561. {
  562. end = true;
  563. result = true;
  564. }
  565. }
  566. }
  567. }
  568. }
  569. };
  570. if (onlyStraight)
  571. gen->foreachDirectNeighbour (currentPos, processNeighbours);
  572. else
  573. gen->foreach_neighbour (currentPos,processNeighbours);
  574. int3 anotherPos(-1, -1, -1);
  575. if (!(result || distance < lastDistance)) //we do not advance, use more advanced pathfinding algorithm?
  576. {
  577. //try any nearby tiles, even if its not closer than current
  578. float lastDistance = 2 * distance; //start with significantly larger value
  579. auto processNeighbours2 = [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  580. {
  581. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  582. {
  583. if (vstd::contains(tileinfo, pos))
  584. {
  585. if (gen->isPossible(pos))
  586. {
  587. if (clearedTiles)
  588. clearedTiles->insert(pos);
  589. anotherPos = pos;
  590. lastDistance = currentPos.dist2dSQ(dst);
  591. }
  592. }
  593. }
  594. };
  595. if (onlyStraight)
  596. gen->foreachDirectNeighbour(currentPos, processNeighbours2);
  597. else
  598. gen->foreach_neighbour(currentPos, processNeighbours2);
  599. if (anotherPos.valid())
  600. {
  601. if (clearedTiles)
  602. clearedTiles->insert(anotherPos);
  603. gen->setOccupied(anotherPos, ETileType::FREE);
  604. currentPos = anotherPos;
  605. }
  606. }
  607. if (!(result || distance < lastDistance || anotherPos.valid()))
  608. {
  609. //FIXME: seemingly this condition is messed up, tells nothing
  610. //logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  611. break;
  612. }
  613. }
  614. return result;
  615. }
  616. bool CRmgTemplateZone::createRoad(CMapGenerator* gen, const int3& src, const int3& dst)
  617. {
  618. //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
  619. std::set<int3> closed; // The set of nodes already evaluated.
  620. std::set<int3> open{src}; // The set of tentative nodes to be evaluated, initially containing the start node
  621. std::map<int3, int3> cameFrom; // The map of navigated nodes.
  622. std::map<int3, float> distances;
  623. int3 currentNode = src;
  624. 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
  625. cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
  626. distances[src] = 0;
  627. // Cost from start along best known path.
  628. // Estimated total cost from start to goal through y.
  629. while (open.size())
  630. {
  631. int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
  632. {
  633. return distances[pos1] < distances[pos2];
  634. });
  635. vstd::erase_if_present (open, currentNode);
  636. closed.insert (currentNode);
  637. if (currentNode == dst || gen->isRoad(currentNode))
  638. {
  639. // The goal node was reached. Trace the path using
  640. // the saved parent information and return path
  641. int3 backTracking = currentNode;
  642. while (cameFrom[backTracking].valid())
  643. {
  644. // add node to path
  645. roads.insert (backTracking);
  646. gen->setRoad (backTracking, ERoadType::COBBLESTONE_ROAD);
  647. //logGlobal->traceStream() << boost::format("Setting road at tile %s") % backTracking;
  648. // do the same for the predecessor
  649. backTracking = cameFrom[backTracking];
  650. }
  651. return true;
  652. }
  653. else
  654. {
  655. bool directNeighbourFound = false;
  656. float movementCost = 1;
  657. auto foo = [gen, this, &open, &closed, &cameFrom, &currentNode, &distances, &dst, &directNeighbourFound, movementCost](int3& pos) -> void
  658. {
  659. int distance = distances[currentNode] + movementCost;
  660. int bestDistanceSoFar = 1e6; //FIXME: boost::limits
  661. auto it = distances.find(pos);
  662. if (it != distances.end())
  663. bestDistanceSoFar = it->second;
  664. if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
  665. {
  666. auto obj = gen->map->getTile(pos).topVisitableObj();
  667. //if (gen->map->checkForVisitableDir(currentNode, &gen->map->getTile(pos), pos)) //TODO: why it has no effect?
  668. if (gen->isFree(pos) || pos == dst || (obj && obj->ID == Obj::MONSTER))
  669. {
  670. if (vstd::contains(this->tileinfo, pos) || pos == dst) //otherwise guard position may appear already connected to other zone.
  671. {
  672. cameFrom[pos] = currentNode;
  673. open.insert(pos);
  674. distances[pos] = distance;
  675. directNeighbourFound = true;
  676. //logGlobal->traceStream() << boost::format("Found connection between node %s and %s, current distance %d") % currentNode % pos % distance;
  677. }
  678. }
  679. }
  680. };
  681. gen->foreachDirectNeighbour (currentNode, foo); // roads cannot be rendered correctly for diagonal directions
  682. if (!directNeighbourFound)
  683. {
  684. movementCost = 2.1f; //moving diagonally is penalized over moving two tiles straight
  685. gen->foreach_neighbour(currentNode, foo);
  686. }
  687. }
  688. }
  689. logGlobal->warnStream() << boost::format("Failed to create road from %s to %s") % src %dst;
  690. return false;
  691. }
  692. bool CRmgTemplateZone::connectPath(CMapGenerator* gen, const int3& src, bool onlyStraight)
  693. ///connect current tile to any other free tile within zone
  694. {
  695. //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
  696. std::set<int3> closed; // The set of nodes already evaluated.
  697. std::set<int3> open{ src }; // The set of tentative nodes to be evaluated, initially containing the start node
  698. std::map<int3, int3> cameFrom; // The map of navigated nodes.
  699. std::map<int3, float> distances;
  700. int3 currentNode = src;
  701. 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
  702. cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
  703. distances[src] = 0;
  704. // Cost from start along best known path.
  705. // Estimated total cost from start to goal through y.
  706. while (open.size())
  707. {
  708. int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
  709. {
  710. return distances[pos1] < distances[pos2];
  711. });
  712. vstd::erase_if_present(open, currentNode);
  713. closed.insert(currentNode);
  714. if (gen->isFree(currentNode))
  715. {
  716. // Trace the path using the saved parent information and return path
  717. int3 backTracking = currentNode;
  718. while (cameFrom[backTracking].valid())
  719. {
  720. gen->setOccupied(backTracking, ETileType::FREE);
  721. backTracking = cameFrom[backTracking];
  722. }
  723. return true;
  724. }
  725. else
  726. {
  727. auto foo = [gen, this, &open, &closed, &cameFrom, &currentNode, &distances](int3& pos) -> void
  728. {
  729. int distance = distances[currentNode] + 1;
  730. int bestDistanceSoFar = 1e6; //FIXME: boost::limits
  731. auto it = distances.find(pos);
  732. if (it != distances.end())
  733. bestDistanceSoFar = it->second;
  734. if (gen->isBlocked(pos)) //no paths through blocked or occupied tiles
  735. return;
  736. if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
  737. {
  738. auto obj = gen->map->getTile(pos).topVisitableObj();
  739. if (vstd::contains(this->tileinfo, pos))
  740. {
  741. cameFrom[pos] = currentNode;
  742. open.insert(pos);
  743. distances[pos] = distance;
  744. }
  745. }
  746. };
  747. if (onlyStraight)
  748. gen->foreachDirectNeighbour(currentNode, foo);
  749. else
  750. gen->foreach_neighbour(currentNode, foo);
  751. }
  752. }
  753. for (auto tile : closed) //these tiles are sealed off and can't be connected anymore
  754. {
  755. //TODO: refactor, unify?
  756. gen->setOccupied (tile, ETileType::BLOCKED);
  757. vstd::erase_if_present(possibleTiles, tile);
  758. }
  759. return false;
  760. }
  761. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  762. {
  763. requiredObjects.push_back(std::make_pair(obj, strength));
  764. }
  765. void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
  766. {
  767. closeObjects.push_back(std::make_pair(obj, strength));
  768. }
  769. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  770. {
  771. //precalculate actual (randomized) monster strength based on this post
  772. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  773. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  774. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  775. static const int value1[] = {2500, 1500, 1000, 500, 0};
  776. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  777. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  778. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  779. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  780. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  781. strength = strength1 + strength2;
  782. if (strength < 2000)
  783. return false; //no guard at all
  784. CreatureID creId = CreatureID::NONE;
  785. int amount = 0;
  786. std::vector<CreatureID> possibleCreatures;
  787. for (auto cre : VLC->creh->creatures)
  788. {
  789. if (cre->special)
  790. continue;
  791. if (!vstd::contains(monsterTypes, cre->faction))
  792. continue;
  793. 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
  794. {
  795. possibleCreatures.push_back(cre->idNumber);
  796. }
  797. }
  798. if (possibleCreatures.size())
  799. {
  800. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  801. amount = strength / VLC->creh->creatures[creId]->AIValue;
  802. if (amount >= 4)
  803. amount *= gen->rand.nextDouble(0.75, 1.25);
  804. }
  805. else //just pick any available creature
  806. {
  807. creId = CreatureID(132); //Azure Dragon
  808. amount = strength / VLC->creh->creatures[creId]->AIValue;
  809. }
  810. auto guard = new CGCreature();
  811. guard->ID = Obj::MONSTER;
  812. guard->subID = creId;
  813. guard->character = CGCreature::HOSTILE;
  814. auto hlp = new CStackInstance(creId, amount);
  815. //will be set during initialization
  816. guard->putStack(SlotID(0), hlp);
  817. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  818. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  819. placeObject(gen, guard, pos);
  820. if (clearSurroundingTiles)
  821. {
  822. //do not spawn anything near monster
  823. gen->foreach_neighbour (pos, [gen](int3 pos)
  824. {
  825. if (gen->isPossible(pos))
  826. gen->setOccupied(pos, ETileType::FREE);
  827. });
  828. }
  829. return true;
  830. }
  831. bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  832. {
  833. CTreasurePileInfo info;
  834. std::map<int3, CGObjectInstance *> treasures;
  835. std::set<int3> boundary;
  836. int3 guardPos (-1,-1,-1);
  837. info.nextTreasurePos = pos;
  838. int maxValue = treasureInfo.max;
  839. int minValue = treasureInfo.min;
  840. ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
  841. int currentValue = 0;
  842. CGObjectInstance * object = nullptr;
  843. while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable
  844. {
  845. treasures[info.nextTreasurePos] = nullptr;
  846. for (auto treasurePos : treasures)
  847. {
  848. gen->foreach_neighbour(treasurePos.first, [gen, &boundary](int3 pos)
  849. {
  850. boundary.insert(pos);
  851. });
  852. }
  853. for (auto treasurePos : treasures)
  854. {
  855. //leaving only boundary around objects
  856. vstd::erase_if_present(boundary, treasurePos.first);
  857. }
  858. for (auto tile : boundary)
  859. {
  860. //we can't extend boundary anymore
  861. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  862. break;
  863. }
  864. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  865. if (!oi.value) //0 value indicates no object
  866. {
  867. vstd::erase_if_present(treasures, info.nextTreasurePos);
  868. break;
  869. }
  870. else
  871. {
  872. object = oi.generateObject();
  873. //remove from possible objects
  874. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  875. assert (oiptr != possibleObjects.end());
  876. oiptr->maxPerZone--;
  877. if (!oiptr->maxPerZone)
  878. possibleObjects.erase(oiptr);
  879. //update treasure pile area
  880. int3 visitablePos = info.nextTreasurePos;
  881. if (oi.templ.isVisitableFromTop())
  882. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  883. else
  884. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  885. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  886. {
  887. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  888. info.occupiedPositions.insert(blockPos);
  889. info.blockedPositions.insert(blockPos);
  890. }
  891. info.occupiedPositions.insert(visitablePos);
  892. currentValue += oi.value;
  893. treasures[info.nextTreasurePos] = object;
  894. //now find place for next object
  895. int3 placeFound(-1,-1,-1);
  896. //randomize next position from among possible ones
  897. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  898. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  899. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  900. {
  901. return lhs.y < rhs.y;
  902. };
  903. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  904. for (auto tile : boundaryCopy)
  905. {
  906. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  907. {
  908. bool here = true;
  909. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  910. {
  911. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  912. here = false;
  913. });
  914. if (here)
  915. {
  916. placeFound = tile;
  917. break;
  918. }
  919. }
  920. }
  921. if (placeFound.valid())
  922. info.nextTreasurePos = placeFound;
  923. else
  924. break; //no more place to add any objects
  925. }
  926. }
  927. if (treasures.size())
  928. {
  929. //find object closest to free path, then connect it to the middle of the zone
  930. int3 closestTile = int3(-1,-1,-1);
  931. float minDistance = 1e10;
  932. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  933. {
  934. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  935. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  936. {
  937. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  938. minDistance = closestFreeTile.dist2d(visitablePos);
  939. }
  940. }
  941. if (!closestTile.valid())
  942. {
  943. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  944. {
  945. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  946. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  947. {
  948. closestTile = visitablePos;
  949. minDistance = closestFreeTile.dist2d(visitablePos);
  950. }
  951. }
  952. }
  953. assert (closestTile.valid());
  954. for (auto tile : info.occupiedPositions)
  955. {
  956. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  957. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  958. }
  959. if (!connectPath (gen, closestTile, false)) //this place is sealed off, need to find new position
  960. {
  961. return false;
  962. }
  963. //update boundary around our objects, including knowledge about objects visitable from bottom
  964. boundary.clear();
  965. for (auto tile : info.visitableFromBottomPositions)
  966. {
  967. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  968. {
  969. if (pos.y >= tile.y) //don't block these objects from above
  970. boundary.insert(pos);
  971. });
  972. }
  973. for (auto tile : info.visitableFromTopPositions)
  974. {
  975. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  976. {
  977. boundary.insert(pos);
  978. });
  979. }
  980. bool isPileGuarded = currentValue >= minGuardedValue;
  981. for (auto tile : boundary) //guard must be standing there
  982. {
  983. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  984. {
  985. guardPos = tile;
  986. break;
  987. }
  988. }
  989. if (guardPos.valid())
  990. {
  991. for (auto treasure : treasures)
  992. {
  993. int3 visitableOffset = treasure.second->getVisitableOffset();
  994. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  995. }
  996. if (addMonster(gen, guardPos, currentValue, false))
  997. {//block only if the object is guarded
  998. for (auto tile : boundary)
  999. {
  1000. if (gen->isPossible(tile))
  1001. gen->setOccupied(tile, ETileType::BLOCKED);
  1002. }
  1003. //do not spawn anything near monster
  1004. gen->foreach_neighbour(guardPos, [gen](int3 pos)
  1005. {
  1006. if (gen->isPossible(pos))
  1007. gen->setOccupied(pos, ETileType::FREE);
  1008. });
  1009. }
  1010. else //mo monster in this pile, make some free space (needed?)
  1011. {
  1012. for (auto tile : boundary)
  1013. if (gen->isPossible(tile))
  1014. gen->setOccupied(tile, ETileType::FREE);
  1015. }
  1016. }
  1017. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  1018. {
  1019. for (auto treasure : treasures)
  1020. {
  1021. if (gen->isPossible(treasure.first))
  1022. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  1023. delete treasure.second;
  1024. }
  1025. }
  1026. return true;
  1027. }
  1028. else //we did not place eveyrthing successfully
  1029. {
  1030. gen->setOccupied(pos, ETileType::BLOCKED); //TODO: refactor stop condition
  1031. vstd::erase_if_present(possibleTiles, pos);
  1032. return false;
  1033. }
  1034. }
  1035. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  1036. {
  1037. //FIXME: handle case that this player is not present -> towns should be set to neutral
  1038. int totalTowns = 0;
  1039. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  1040. {
  1041. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  1042. for (auto tile : town->getBlockedPos())
  1043. {
  1044. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  1045. {
  1046. if (gen->isPossible(pos))
  1047. {
  1048. gen->setOccupied(pos, ETileType::FREE);
  1049. }
  1050. });
  1051. }
  1052. };
  1053. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  1054. {
  1055. for (int i = 0; i < count; i++)
  1056. {
  1057. auto town = new CGTownInstance();
  1058. town->ID = Obj::TOWN;
  1059. if (this->townsAreSameType)
  1060. town->subID = townType;
  1061. else
  1062. {
  1063. if (townTypes.size())
  1064. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1065. else
  1066. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  1067. }
  1068. town->tempOwner = player;
  1069. if (hasFort)
  1070. town->builtBuildings.insert(BuildingID::FORT);
  1071. town->builtBuildings.insert(BuildingID::DEFAULT);
  1072. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  1073. {
  1074. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  1075. town->possibleSpells.push_back(spell->id);
  1076. }
  1077. if (!totalTowns)
  1078. {
  1079. //first town in zone sets the facton of entire zone
  1080. town->subID = townType;
  1081. //register MAIN town of zone
  1082. gen->registerZone(town->subID);
  1083. //first town in zone goes in the middle
  1084. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  1085. cutPathAroundTown(town);
  1086. }
  1087. else
  1088. addRequiredObject (town);
  1089. totalTowns++;
  1090. }
  1091. };
  1092. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  1093. {
  1094. //set zone types to player faction, generate main town
  1095. logGlobal->infoStream() << "Preparing playing zone";
  1096. int player_id = *owner - 1;
  1097. auto & playerInfo = gen->map->players[player_id];
  1098. PlayerColor player(player_id);
  1099. if (playerInfo.canAnyonePlay())
  1100. {
  1101. player = PlayerColor(player_id);
  1102. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  1103. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  1104. randomizeTownType(gen);
  1105. }
  1106. else //no player - randomize town
  1107. {
  1108. player = PlayerColor::NEUTRAL;
  1109. randomizeTownType(gen);
  1110. }
  1111. auto town = new CGTownInstance();
  1112. town->ID = Obj::TOWN;
  1113. town->subID = townType;
  1114. town->tempOwner = player;
  1115. town->builtBuildings.insert(BuildingID::FORT);
  1116. town->builtBuildings.insert(BuildingID::DEFAULT);
  1117. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  1118. {
  1119. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  1120. town->possibleSpells.push_back(spell->id);
  1121. }
  1122. //towns are big objects and should be centered around visitable position
  1123. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  1124. cutPathAroundTown(town);
  1125. totalTowns++;
  1126. //register MAIN town of zone only
  1127. gen->registerZone (town->subID);
  1128. if (playerInfo.canAnyonePlay()) //configure info for owning player
  1129. {
  1130. logGlobal->traceStream() << "Fill player info " << player_id;
  1131. // Update player info
  1132. playerInfo.allowedFactions.clear();
  1133. playerInfo.allowedFactions.insert(townType);
  1134. playerInfo.hasMainTown = true;
  1135. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  1136. playerInfo.generateHeroAtMainTown = true;
  1137. //now create actual towns
  1138. addNewTowns(playerTowns.getCastleCount() - 1, true, player);
  1139. addNewTowns(playerTowns.getTownCount(), false, player);
  1140. }
  1141. else
  1142. {
  1143. addNewTowns(playerTowns.getCastleCount() - 1, true, PlayerColor::NEUTRAL);
  1144. addNewTowns(playerTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1145. }
  1146. }
  1147. else //randomize town types for any other zones as well
  1148. {
  1149. randomizeTownType(gen);
  1150. }
  1151. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  1152. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1153. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  1154. {
  1155. //25% chance for neutral
  1156. if (gen->rand.nextInt(1, 100) <= 25)
  1157. {
  1158. townType = ETownType::NEUTRAL;
  1159. }
  1160. else
  1161. {
  1162. if (townTypes.size())
  1163. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1164. else if (monsterTypes.size())
  1165. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  1166. else //just in any case
  1167. randomizeTownType(gen);
  1168. }
  1169. }
  1170. }
  1171. void CRmgTemplateZone::randomizeTownType (CMapGenerator* gen)
  1172. {
  1173. if (townTypes.size())
  1174. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1175. else
  1176. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed, we still need some
  1177. }
  1178. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  1179. {
  1180. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  1181. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  1182. else
  1183. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  1184. //TODO: allow new types of terrain?
  1185. if (pos.z)
  1186. {
  1187. if (terrainType != ETerrainType::LAVA)
  1188. terrainType = ETerrainType::SUBTERRANEAN;
  1189. }
  1190. else
  1191. {
  1192. if (terrainType == ETerrainType::SUBTERRANEAN)
  1193. terrainType = ETerrainType::DIRT;
  1194. }
  1195. paintZoneTerrain (gen, terrainType);
  1196. }
  1197. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  1198. {
  1199. std::vector<int3> tiles;
  1200. for (auto tile : tileinfo)
  1201. {
  1202. tiles.push_back (tile);
  1203. }
  1204. gen->editManager->getTerrainSelection().setSelection(tiles);
  1205. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1206. }
  1207. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  1208. {
  1209. std::vector<Res::ERes> required_mines;
  1210. required_mines.push_back(Res::ERes::WOOD);
  1211. required_mines.push_back(Res::ERes::ORE);
  1212. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1213. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1214. for (const auto & res : woodOre)
  1215. {
  1216. for (int i = 0; i < mines[res]; i++)
  1217. {
  1218. auto mine = new CGMine();
  1219. mine->ID = Obj::MINE;
  1220. mine->subID = static_cast<si32>(res);
  1221. mine->producedResource = res;
  1222. mine->producedQuantity = mine->defaultResProduction();
  1223. addCloseObject(mine, 1500);
  1224. }
  1225. }
  1226. for (const auto & res : preciousResources)
  1227. {
  1228. for (int i = 0; i < mines[res]; i++)
  1229. {
  1230. auto mine = new CGMine();
  1231. mine->ID = Obj::MINE;
  1232. mine->subID = static_cast<si32>(res);
  1233. mine->producedResource = res;
  1234. mine->producedQuantity = mine->defaultResProduction();
  1235. addRequiredObject(mine, 3500);
  1236. }
  1237. }
  1238. for (int i = 0; i < mines[Res::GOLD]; i++)
  1239. {
  1240. auto mine = new CGMine();
  1241. mine->ID = Obj::MINE;
  1242. mine->subID = static_cast<si32>(Res::GOLD);
  1243. mine->producedResource = Res::GOLD;
  1244. mine->producedQuantity = mine->defaultResProduction();
  1245. addRequiredObject(mine, 7000);
  1246. }
  1247. return true;
  1248. }
  1249. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1250. {
  1251. logGlobal->traceStream() << "Creating required objects";
  1252. for(const auto &object : requiredObjects)
  1253. {
  1254. auto obj = object.first;
  1255. int3 pos;
  1256. int3 accessibleOffset;
  1257. while (true)
  1258. {
  1259. if (!findPlaceForObject(gen, obj, 3, pos))
  1260. {
  1261. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1262. return false;
  1263. }
  1264. //check if we can find a path around this object. Tiles will be set to "USED" after object is successfully placed.
  1265. obj->pos = pos;
  1266. gen->setOccupied (obj->visitablePos(), ETileType::BLOCKED);
  1267. for (auto tile : obj->getBlockedPos())
  1268. {
  1269. if (gen->map->isInTheMap(tile))
  1270. gen->setOccupied(tile, ETileType::BLOCKED);
  1271. }
  1272. accessibleOffset = getAccessibleOffset(gen, obj->appearance, pos, obj->getBlockedOffsets());
  1273. if (!accessibleOffset.valid())
  1274. {
  1275. logGlobal->warnStream() << boost::format("Cannot access required object at position %s, retrying") % pos;
  1276. continue;
  1277. }
  1278. if (!connectPath(gen, accessibleOffset, true))
  1279. {
  1280. logGlobal->warnStream() << boost::format("Failed to create path to required object at position %s, retrying") % pos;
  1281. continue;
  1282. }
  1283. else
  1284. break;
  1285. }
  1286. placeObject(gen, obj, pos);
  1287. guardObject (gen, obj, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY), true);
  1288. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1289. }
  1290. for (const auto &obj : closeObjects)
  1291. {
  1292. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1293. // smallest distance to zone center, greatest distance to nearest object
  1294. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1295. {
  1296. return (this->pos.dist2dSQ(lhs) * 0.5f - gen->getNearestObjectDistance(lhs)) < (this->pos.dist2dSQ(rhs) * 0.5f - gen->getNearestObjectDistance(rhs));
  1297. };
  1298. boost::sort (tiles, isCloser);
  1299. setTemplateForObject(gen, obj.first);
  1300. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1301. bool result = false;
  1302. for (auto tile : tiles)
  1303. {
  1304. //object must be accessible from at least one surounding tile
  1305. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile, tilesBlockedByObject))
  1306. continue;
  1307. //avoid borders
  1308. if (gen->isPossible(tile))
  1309. {
  1310. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1311. {
  1312. placeObject(gen, obj.first, tile);
  1313. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1314. result = true;
  1315. break;
  1316. }
  1317. }
  1318. }
  1319. if (!result)
  1320. {
  1321. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1322. //TODO CLEANUP!
  1323. return false;
  1324. }
  1325. }
  1326. return true;
  1327. }
  1328. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1329. {
  1330. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  1331. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1332. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1333. minGuardedValue = minGuardedValues[monsterStrength];
  1334. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1335. {
  1336. return lhs.max > rhs.max;
  1337. };
  1338. //place biggest treasures first at large distance, place smaller ones inbetween
  1339. boost::sort(treasureInfo, valueComparator);
  1340. int totalDensity = 0;
  1341. for (auto t : treasureInfo)
  1342. {
  1343. //discard objects with too high value to be ever placed
  1344. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  1345. {
  1346. return oi.value > t.max;
  1347. });
  1348. totalDensity += t.density;
  1349. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1350. //also, normalize it to zone count - higher count means relatively smaller zones
  1351. //this is squared distance for optimization purposes
  1352. const double minDistance = std::max<float>((125.f / totalDensity), 2);
  1353. //distance lower than 2 causes objects to overlap and crash
  1354. bool stop = false;
  1355. do {
  1356. //optimization - don't check tiles which are not allowed
  1357. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1358. {
  1359. return !gen->isPossible(tile);
  1360. });
  1361. int3 treasureTilePos;
  1362. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1363. do
  1364. {
  1365. if (!findPlaceForTreasurePile(gen, minDistance, treasureTilePos, t.min))
  1366. {
  1367. stop = true;
  1368. break;
  1369. }
  1370. }
  1371. while (!createTreasurePile(gen, treasureTilePos, minDistance, t)); //failed creation - position was wrong, cannot connect it
  1372. } while (!stop);
  1373. }
  1374. }
  1375. void CRmgTemplateZone::createObstacles1(CMapGenerator * gen)
  1376. {
  1377. if (pos.z) //underground
  1378. {
  1379. //now make sure all accessible tiles have no additional rock on them
  1380. std::vector<int3> accessibleTiles;
  1381. for (auto tile : tileinfo)
  1382. {
  1383. if (gen->isFree(tile) || gen->isUsed(tile))
  1384. {
  1385. accessibleTiles.push_back(tile);
  1386. }
  1387. }
  1388. gen->editManager->getTerrainSelection().setSelection(accessibleTiles);
  1389. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1390. }
  1391. }
  1392. void CRmgTemplateZone::createObstacles2(CMapGenerator* gen)
  1393. {
  1394. typedef std::vector<ObjectTemplate> obstacleVector;
  1395. //obstacleVector possibleObstacles;
  1396. std::map <ui8, obstacleVector> obstaclesBySize;
  1397. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1398. std::vector<obstaclePair> possibleObstacles;
  1399. //get all possible obstacles for this terrain
  1400. for (auto primaryID : VLC->objtypeh->knownObjects())
  1401. {
  1402. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1403. {
  1404. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1405. if (handler->isStaticObject())
  1406. {
  1407. for (auto temp : handler->getTemplates())
  1408. {
  1409. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1410. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1411. }
  1412. }
  1413. }
  1414. }
  1415. for (auto o : obstaclesBySize)
  1416. {
  1417. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1418. }
  1419. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1420. {
  1421. return p1.first > p2.first; //bigger obstacles first
  1422. });
  1423. auto sel = gen->editManager->getTerrainSelection();
  1424. sel.clearSelection();
  1425. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1426. {
  1427. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1428. int3 obstaclePos = tile + temp.getBlockMapOffset();
  1429. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1430. {
  1431. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1432. placeObject(gen, obj, obstaclePos, false);
  1433. return true;
  1434. }
  1435. return false;
  1436. };
  1437. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1438. for (auto tile : boost::adaptors::reverse(tileinfo))
  1439. {
  1440. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1441. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1442. {
  1443. //start from biggets obstacles
  1444. for (int i = 0; i < possibleObstacles.size(); i++)
  1445. {
  1446. if (tryToPlaceObstacleHere(tile, i))
  1447. break;
  1448. }
  1449. }
  1450. }
  1451. //cleanup - remove unused possible tiles to make space for roads
  1452. for (auto tile : tileinfo)
  1453. {
  1454. if (gen->isPossible(tile))
  1455. {
  1456. gen->setOccupied (tile, ETileType::FREE);
  1457. }
  1458. }
  1459. }
  1460. void CRmgTemplateZone::connectRoads(CMapGenerator* gen)
  1461. {
  1462. logGlobal->debug("Started building roads");
  1463. std::set<int3> roadNodesCopy(roadNodes);
  1464. std::set<int3> processed;
  1465. while(!roadNodesCopy.empty())
  1466. {
  1467. int3 node = *roadNodesCopy.begin();
  1468. roadNodesCopy.erase(node);
  1469. int3 cross(-1, -1, -1);
  1470. auto comparator = [=](int3 lhs, int3 rhs) { return node.dist2dSQ(lhs) < node.dist2dSQ(rhs); };
  1471. if (processed.size()) //connect with already existing network
  1472. {
  1473. cross = *boost::range::min_element(processed, comparator); //find another remaining node
  1474. }
  1475. else if (roadNodesCopy.size()) //connect with any other unconnected node
  1476. {
  1477. cross = *boost::range::min_element(roadNodesCopy, comparator); //find another remaining node
  1478. }
  1479. else //no other nodes left, for example single road node in this zone
  1480. break;
  1481. logGlobal->debugStream() << "Building road from " << node << " to " << cross;
  1482. if (createRoad(gen, node, cross))
  1483. {
  1484. processed.insert(cross); //don't draw road starting at end point which is already connected
  1485. vstd::erase_if_present(roadNodesCopy, cross);
  1486. }
  1487. processed.insert(node);
  1488. }
  1489. drawRoads(gen);
  1490. logGlobal->debug("Finished building roads");
  1491. }
  1492. void CRmgTemplateZone::drawRoads(CMapGenerator* gen)
  1493. {
  1494. std::vector<int3> tiles;
  1495. for (auto tile : roads)
  1496. {
  1497. if(gen->map->isInTheMap(tile))
  1498. tiles.push_back (tile);
  1499. }
  1500. for (auto tile : roadNodes)
  1501. {
  1502. if (vstd::contains(tileinfo, tile)) //mark roads for our nodes, but not for zone guards in other zones
  1503. tiles.push_back(tile);
  1504. }
  1505. gen->editManager->getTerrainSelection().setSelection(tiles);
  1506. gen->editManager->drawRoad(ERoadType::COBBLESTONE_ROAD, &gen->rand);
  1507. }
  1508. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1509. {
  1510. initTerrainType(gen);
  1511. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1512. addAllPossibleObjects (gen);
  1513. fractalize(gen);
  1514. placeMines(gen);
  1515. createRequiredObjects(gen);
  1516. createTreasures(gen);
  1517. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1518. return true;
  1519. }
  1520. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1521. {
  1522. float best_distance = 0;
  1523. bool result = false;
  1524. bool needsGuard = value > minGuardedValue;
  1525. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1526. for(auto tile : possibleTiles)
  1527. {
  1528. auto dist = gen->getNearestObjectDistance(tile);
  1529. if ((dist >= min_dist) && (dist > best_distance))
  1530. {
  1531. bool allTilesAvailable = true;
  1532. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1533. {
  1534. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1535. {
  1536. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1537. }
  1538. });
  1539. if (allTilesAvailable)
  1540. {
  1541. best_distance = dist;
  1542. pos = tile;
  1543. result = true;
  1544. }
  1545. }
  1546. }
  1547. if (result)
  1548. {
  1549. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1550. }
  1551. return result;
  1552. }
  1553. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1554. {
  1555. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1556. return false;
  1557. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1558. for (auto blockingTile : tilesBlockedByObject)
  1559. {
  1560. int3 t = pos + blockingTile;
  1561. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1562. {
  1563. return false; //if at least one tile is not possible, object can't be placed here
  1564. }
  1565. }
  1566. return true;
  1567. }
  1568. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1569. {
  1570. return getAccessibleOffset(gen, appearance, tile, tilesBlockedByObject).valid();
  1571. }
  1572. int3 CRmgTemplateZone::getAccessibleOffset(CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1573. {
  1574. int3 ret(-1, -1, -1);
  1575. for (int x = -1; x < 2; x++)
  1576. {
  1577. for (int y = -1; y <2; y++)
  1578. {
  1579. if (x && y) //check only if object is visitable from another tile
  1580. {
  1581. int3 offset = int3(x, y, 0) - appearance.getVisitableOffset();
  1582. if (!vstd::contains(tilesBlockedByObject, offset))
  1583. {
  1584. int3 nearbyPos = tile + offset;
  1585. if (gen->map->isInTheMap(nearbyPos))
  1586. {
  1587. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1588. ret = nearbyPos;
  1589. }
  1590. }
  1591. }
  1592. };
  1593. }
  1594. return ret;
  1595. }
  1596. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1597. {
  1598. if (obj->appearance.id == Obj::NO_OBJ)
  1599. {
  1600. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1601. if (templates.empty())
  1602. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1603. obj->appearance = templates.front();
  1604. }
  1605. }
  1606. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1607. {
  1608. for (auto blockingTile : tilesBlockedByObject)
  1609. {
  1610. int3 t = tile + blockingTile;
  1611. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1612. {
  1613. //if at least one tile is not possible, object can't be placed here
  1614. return false;
  1615. }
  1616. }
  1617. return true;
  1618. }
  1619. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1620. {
  1621. //we need object apperance to deduce free tile
  1622. setTemplateForObject(gen, obj);
  1623. //si32 min_dist = sqrt(tileinfo.size()/density);
  1624. int best_distance = 0;
  1625. bool result = false;
  1626. //si32 w = gen->map->width;
  1627. //si32 h = gen->map->height;
  1628. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1629. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1630. for (auto tile : tileinfo)
  1631. {
  1632. //object must be accessible from at least one surounding tile
  1633. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1634. continue;
  1635. auto ti = gen->getTile(tile);
  1636. auto dist = ti.getNearestObjectDistance();
  1637. //avoid borders
  1638. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1639. {
  1640. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1641. {
  1642. best_distance = dist;
  1643. pos = tile;
  1644. result = true;
  1645. }
  1646. }
  1647. }
  1648. if (result)
  1649. {
  1650. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1651. }
  1652. return result;
  1653. }
  1654. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1655. {
  1656. if (!gen->map->isInTheMap(pos))
  1657. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1658. object->pos = pos;
  1659. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1660. 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()));
  1661. for (auto tile : object->getBlockedPos())
  1662. {
  1663. if (!gen->map->isInTheMap(tile))
  1664. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1665. }
  1666. if (object->appearance.id == Obj::NO_OBJ)
  1667. {
  1668. auto terrainType = gen->map->getTile(pos).terType;
  1669. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1670. if (templates.empty())
  1671. 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));
  1672. object->appearance = templates.front();
  1673. }
  1674. gen->editManager->insertObject(object, pos);
  1675. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1676. }
  1677. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1678. {
  1679. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1680. checkAndPlaceObject (gen, object, pos);
  1681. auto points = object->getBlockedPos();
  1682. if (object->isVisitable())
  1683. points.insert(pos + object->getVisitableOffset());
  1684. points.insert(pos);
  1685. for(auto p : points)
  1686. {
  1687. if (gen->map->isInTheMap(p))
  1688. {
  1689. gen->setOccupied(p, ETileType::USED);
  1690. }
  1691. }
  1692. if (updateDistance)
  1693. {
  1694. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1695. {
  1696. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1697. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1698. }
  1699. }
  1700. if (object->ID == Obj::SEER_HUT) //debug
  1701. {
  1702. CGSeerHut * sh = dynamic_cast<CGSeerHut *>(object);
  1703. auto artid = sh->quest->m5arts.front();
  1704. logGlobal->warnStream() << boost::format("Placed Seer Hut at %s, quest artifact %d is %s") % object->pos % artid % VLC->arth->artifacts[artid]->Name();
  1705. }
  1706. switch (object->ID)
  1707. {
  1708. case Obj::TOWN:
  1709. case Obj::RANDOM_TOWN:
  1710. case Obj::MONOLITH_TWO_WAY:
  1711. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  1712. case Obj::MONOLITH_ONE_WAY_EXIT:
  1713. case Obj::SUBTERRANEAN_GATE:
  1714. {
  1715. addRoadNode(object->visitablePos());
  1716. }
  1717. break;
  1718. default:
  1719. break;
  1720. }
  1721. }
  1722. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1723. {
  1724. placeObject(gen, object, pos);
  1725. guardObject(gen, object, str, zoneGuard);
  1726. }
  1727. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1728. {
  1729. //get all tiles from which this object can be accessed
  1730. int3 visitable = object->visitablePos();
  1731. std::vector<int3> tiles;
  1732. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1733. gen->foreach_neighbour(visitable, [&](int3& pos)
  1734. {
  1735. if (gen->isPossible(pos) || gen->isFree(pos))
  1736. {
  1737. if (!vstd::contains(tilesBlockedByObject, pos))
  1738. {
  1739. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1740. {
  1741. tiles.push_back(pos);
  1742. }
  1743. }
  1744. };
  1745. });
  1746. return tiles;
  1747. }
  1748. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1749. {
  1750. std::vector<int3> tiles = getAccessibleOffsets(gen, object);
  1751. int3 guardTile(-1, -1, -1);
  1752. if (tiles.size())
  1753. {
  1754. guardTile = tiles.front();
  1755. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1756. }
  1757. else
  1758. {
  1759. logGlobal->errorStream() << boost::format("Failed to guard object at %s") % object->pos();
  1760. return false;
  1761. }
  1762. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1763. {
  1764. for (auto pos : tiles)
  1765. {
  1766. if (!gen->isFree(pos))
  1767. gen->setOccupied(pos, ETileType::BLOCKED);
  1768. }
  1769. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1770. {
  1771. if (gen->isPossible(pos))
  1772. gen->setOccupied (pos, ETileType::FREE);
  1773. });
  1774. gen->setOccupied (guardTile, ETileType::USED);
  1775. }
  1776. else //allow no guard or other object in front of this object
  1777. {
  1778. for (auto tile : tiles)
  1779. if (gen->isPossible(tile))
  1780. gen->setOccupied (tile, ETileType::FREE);
  1781. }
  1782. return true;
  1783. }
  1784. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1785. {
  1786. //int objectsVisitableFromBottom = 0; //for debug
  1787. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1788. ui32 total = 0;
  1789. //calculate actual treasure value range based on remaining value
  1790. ui32 maxVal = desiredValue - currentValue;
  1791. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1792. //roulette wheel
  1793. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1794. {
  1795. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1796. {
  1797. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1798. int3 newVisitablePos = info.nextTreasurePos;
  1799. if (!oi.templ.isVisitableFromTop())
  1800. {
  1801. //objectsVisitableFromBottom++;
  1802. //there must be free tiles under object
  1803. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1804. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1805. continue;
  1806. }
  1807. //NOTE: y coordinate grows downwards
  1808. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1809. {
  1810. bool fitsHere = false;
  1811. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1812. {
  1813. for (auto tile : info.visitableFromTopPositions)
  1814. {
  1815. int3 actualTile = tile + newVisitableOffset;
  1816. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1817. {
  1818. fitsHere = true;
  1819. break;
  1820. }
  1821. }
  1822. for (auto tile : info.visitableFromBottomPositions)
  1823. {
  1824. int3 actualTile = tile + newVisitableOffset;
  1825. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1826. {
  1827. fitsHere = true;
  1828. break;
  1829. }
  1830. }
  1831. }
  1832. else //if new object is not visitable from top, it must be accessible from below or side
  1833. {
  1834. for (auto tile : info.visitableFromTopPositions)
  1835. {
  1836. int3 actualTile = tile + newVisitableOffset;
  1837. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1838. {
  1839. fitsHere = true;
  1840. break;
  1841. }
  1842. }
  1843. for (auto tile : info.visitableFromBottomPositions)
  1844. {
  1845. int3 actualTile = tile + newVisitableOffset;
  1846. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1847. {
  1848. fitsHere = true;
  1849. break;
  1850. }
  1851. }
  1852. }
  1853. if (!fitsHere)
  1854. continue;
  1855. }
  1856. //now check blockmap, including our already reserved pile area
  1857. bool fitsBlockmap = true;
  1858. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1859. blockedOffsets.insert (newVisitableOffset);
  1860. for (auto blockingTile : blockedOffsets)
  1861. {
  1862. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1863. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1864. {
  1865. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1866. break;
  1867. }
  1868. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1869. {
  1870. fitsBlockmap = false;
  1871. break;
  1872. }
  1873. }
  1874. if (!fitsBlockmap)
  1875. continue;
  1876. total += oi.probability;
  1877. //assert (oi.value > 0);
  1878. tresholds.push_back (std::make_pair (total, oi));
  1879. }
  1880. }
  1881. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1882. if (tresholds.empty())
  1883. {
  1884. ObjectInfo oi;
  1885. //Generate pandora Box with gold if the value is extremely high
  1886. if (minValue > 20000) //we don't have object valuable enough
  1887. {
  1888. oi.generateObject = [minValue]() -> CGObjectInstance *
  1889. {
  1890. auto obj = new CGPandoraBox();
  1891. obj->ID = Obj::PANDORAS_BOX;
  1892. obj->subID = 0;
  1893. obj->resources[Res::GOLD] = minValue;
  1894. return obj;
  1895. };
  1896. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1897. oi.value = minValue;
  1898. oi.probability = 0;
  1899. }
  1900. else //generate empty object with 0 value if the value if we can't spawn anything
  1901. {
  1902. oi.generateObject = [gen]() -> CGObjectInstance *
  1903. {
  1904. return nullptr;
  1905. };
  1906. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1907. oi.value = 0; // this field is checked to determine no object
  1908. oi.probability = 0;
  1909. }
  1910. return oi;
  1911. }
  1912. else
  1913. {
  1914. int r = gen->rand.nextInt (1, total);
  1915. for (auto t : tresholds)
  1916. {
  1917. if (r <= t.first)
  1918. return t.second;
  1919. }
  1920. assert (0); //we should never be here
  1921. }
  1922. //FIXME: control reaches end of non-void function. Missing return?
  1923. }
  1924. void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
  1925. {
  1926. ObjectInfo oi;
  1927. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1928. int numZones = gen->getZones().size();
  1929. std::vector<CCreature *> creatures; //native creatures for this zone
  1930. for (auto cre : VLC->creh->creatures)
  1931. {
  1932. if (!cre->special && cre->faction == townType)
  1933. {
  1934. creatures.push_back(cre);
  1935. }
  1936. }
  1937. for (auto primaryID : VLC->objtypeh->knownObjects())
  1938. {
  1939. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1940. {
  1941. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1942. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1943. {
  1944. for (auto temp : handler->getTemplates())
  1945. {
  1946. if (temp.canBePlacedAt(terrainType))
  1947. {
  1948. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1949. {
  1950. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1951. };
  1952. auto rmgInfo = handler->getRMGInfo();
  1953. oi.value = rmgInfo.value;
  1954. oi.probability = rmgInfo.rarity;
  1955. oi.templ = temp;
  1956. oi.maxPerZone = rmgInfo.zoneLimit;
  1957. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1958. possibleObjects.push_back(oi);
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. //prisons
  1965. //levels 1, 5, 10, 20, 30
  1966. static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
  1967. static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
  1968. for (int i = 0; i < 5; i++)
  1969. {
  1970. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1971. {
  1972. auto obj = new CGHeroInstance;
  1973. obj->ID = Obj::PRISON;
  1974. std::vector<ui32> possibleHeroes;
  1975. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1976. {
  1977. if (gen->map->allowedHeroes[j])
  1978. possibleHeroes.push_back(j);
  1979. }
  1980. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1981. obj->subID = hid; //will be initialized later
  1982. obj->exp = prisonExp[i];
  1983. obj->setOwner(PlayerColor::NEUTRAL);
  1984. gen->map->allowedHeroes[hid] = false; //ban this hero
  1985. gen->decreasePrisonsRemaining();
  1986. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1987. return obj;
  1988. };
  1989. oi.setTemplate(Obj::PRISON, 0, terrainType);
  1990. oi.value = prisonValues[i];
  1991. oi.probability = 30;
  1992. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1993. possibleObjects.push_back(oi);
  1994. }
  1995. //all following objects are unlimited
  1996. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1997. //dwellings
  1998. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1999. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  2000. static int elementalConfluxROE[] = { 7, 13, 16, 47 };
  2001. for (int i = 0; i < 4; i++)
  2002. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  2003. for (auto secondaryID : subObjects)
  2004. {
  2005. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  2006. auto creatures = dwellingHandler->getProducedCreatures();
  2007. if (creatures.empty())
  2008. continue;
  2009. auto cre = creatures.front();
  2010. if (cre->faction == townType)
  2011. {
  2012. float nativeZonesCount = gen->getZoneCount(cre->faction);
  2013. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  2014. oi.probability = 40;
  2015. for (auto temp : dwellingHandler->getTemplates())
  2016. {
  2017. if (temp.canBePlacedAt(terrainType))
  2018. {
  2019. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  2020. {
  2021. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  2022. //dwellingHandler->configureObject(obj, gen->rand);
  2023. obj->tempOwner = PlayerColor::NEUTRAL;
  2024. return obj;
  2025. };
  2026. oi.templ = temp;
  2027. possibleObjects.push_back(oi);
  2028. }
  2029. }
  2030. }
  2031. }
  2032. static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
  2033. for (int i = 0; i < 5; i++)
  2034. {
  2035. oi.generateObject = [i, gen]() -> CGObjectInstance *
  2036. {
  2037. auto obj = new CGArtifact();
  2038. obj->ID = Obj::SPELL_SCROLL;
  2039. obj->subID = 0;
  2040. std::vector<SpellID> out;
  2041. //TODO: unify with cb->getAllowedSpells?
  2042. for (ui32 spellid = 0; spellid < gen->map->allowedSpell.size(); spellid++) //spellh size appears to be greater (?)
  2043. {
  2044. const CSpell *spell = SpellID(spellid).toSpell();
  2045. if (gen->map->allowedSpell[spell->id] && spell->level == i + 1)
  2046. {
  2047. out.push_back(spell->id);
  2048. }
  2049. }
  2050. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  2051. gen->map->addNewArtifactInstance(a);
  2052. obj->storedArtifact = a;
  2053. return obj;
  2054. };
  2055. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  2056. oi.value = scrollValues[i];
  2057. oi.probability = 30;
  2058. possibleObjects.push_back(oi);
  2059. }
  2060. //pandora box with gold
  2061. for (int i = 1; i < 5; i++)
  2062. {
  2063. oi.generateObject = [i]() -> CGObjectInstance *
  2064. {
  2065. auto obj = new CGPandoraBox();
  2066. obj->ID = Obj::PANDORAS_BOX;
  2067. obj->subID = 0;
  2068. obj->resources[Res::GOLD] = i * 5000;
  2069. return obj;
  2070. };
  2071. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2072. oi.value = i * 5000;;
  2073. oi.probability = 5;
  2074. possibleObjects.push_back(oi);
  2075. }
  2076. //pandora box with experience
  2077. for (int i = 1; i < 5; i++)
  2078. {
  2079. oi.generateObject = [i]() -> CGObjectInstance *
  2080. {
  2081. auto obj = new CGPandoraBox();
  2082. obj->ID = Obj::PANDORAS_BOX;
  2083. obj->subID = 0;
  2084. obj->gainedExp = i * 5000;
  2085. return obj;
  2086. };
  2087. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2088. oi.value = i * 6000;;
  2089. oi.probability = 20;
  2090. possibleObjects.push_back(oi);
  2091. }
  2092. //pandora box with creatures
  2093. static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
  2094. auto creatureToCount = [](CCreature * creature) -> int
  2095. {
  2096. int actualTier = creature->level > 7 ? 6 : creature->level - 1;
  2097. float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
  2098. if (creaturesAmount <= 5)
  2099. {
  2100. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  2101. if (creaturesAmount < 1)
  2102. return 0;
  2103. }
  2104. else if (creaturesAmount <= 12)
  2105. {
  2106. (creaturesAmount /= 2) *= 2;
  2107. }
  2108. else if (creaturesAmount <= 50)
  2109. {
  2110. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  2111. }
  2112. else
  2113. {
  2114. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  2115. }
  2116. return creaturesAmount;
  2117. };
  2118. for (auto creature : creatures)
  2119. {
  2120. int creaturesAmount = creatureToCount(creature);
  2121. if (!creaturesAmount)
  2122. continue;
  2123. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  2124. {
  2125. auto obj = new CGPandoraBox();
  2126. obj->ID = Obj::PANDORAS_BOX;
  2127. obj->subID = 0;
  2128. auto stack = new CStackInstance(creature, creaturesAmount);
  2129. obj->creatures.putStack(SlotID(0), stack);
  2130. return obj;
  2131. };
  2132. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2133. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
  2134. oi.probability = 3;
  2135. possibleObjects.push_back(oi);
  2136. }
  2137. //Pandora with 12 spells of certain level
  2138. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  2139. {
  2140. oi.generateObject = [i, gen]() -> CGObjectInstance *
  2141. {
  2142. auto obj = new CGPandoraBox();
  2143. obj->ID = Obj::PANDORAS_BOX;
  2144. obj->subID = 0;
  2145. std::vector <CSpell *> spells;
  2146. for (auto spell : VLC->spellh->objects)
  2147. {
  2148. if (!spell->isSpecialSpell() && spell->level == i)
  2149. spells.push_back(spell);
  2150. }
  2151. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2152. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  2153. {
  2154. obj->spells.push_back(spells[j]->id);
  2155. }
  2156. return obj;
  2157. };
  2158. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2159. oi.value = (i + 1) * 2500; //5000 - 15000
  2160. oi.probability = 2;
  2161. possibleObjects.push_back(oi);
  2162. }
  2163. //Pandora with 15 spells of certain school
  2164. for (int i = 0; i < 4; i++)
  2165. {
  2166. oi.generateObject = [i,gen]() -> CGObjectInstance *
  2167. {
  2168. auto obj = new CGPandoraBox();
  2169. obj->ID = Obj::PANDORAS_BOX;
  2170. obj->subID = 0;
  2171. std::vector <CSpell *> spells;
  2172. for (auto spell : VLC->spellh->objects)
  2173. {
  2174. if (!spell->isSpecialSpell() && spell->school[(ESpellSchool)i])
  2175. spells.push_back(spell);
  2176. }
  2177. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2178. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  2179. {
  2180. obj->spells.push_back(spells[j]->id);
  2181. }
  2182. return obj;
  2183. };
  2184. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2185. oi.value = 15000;
  2186. oi.probability = 2;
  2187. possibleObjects.push_back(oi);
  2188. }
  2189. // Pandora box with 60 random spells
  2190. oi.generateObject = [gen]() -> CGObjectInstance *
  2191. {
  2192. auto obj = new CGPandoraBox();
  2193. obj->ID = Obj::PANDORAS_BOX;
  2194. obj->subID = 0;
  2195. std::vector <CSpell *> spells;
  2196. for (auto spell : VLC->spellh->objects)
  2197. {
  2198. if (!spell->isSpecialSpell())
  2199. spells.push_back(spell);
  2200. }
  2201. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2202. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  2203. {
  2204. obj->spells.push_back(spells[j]->id);
  2205. }
  2206. return obj;
  2207. };
  2208. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2209. oi.value = 30000;
  2210. oi.probability = 2;
  2211. possibleObjects.push_back(oi);
  2212. //seer huts with creatures or generic rewards
  2213. //if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  2214. if (false) //FIXME: Seer Huts are bugged
  2215. {
  2216. static const int genericSeerHuts = 8;
  2217. int seerHutsPerType = 0;
  2218. const int questArtsRemaining = gen->getQuestArtsRemaning().size();
  2219. //general issue is that not many artifact types are available for quests
  2220. if (questArtsRemaining >= genericSeerHuts + creatures.size())
  2221. {
  2222. seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
  2223. }
  2224. else if (questArtsRemaining >= genericSeerHuts)
  2225. {
  2226. seerHutsPerType = 1;
  2227. }
  2228. oi.maxPerZone = seerHutsPerType;
  2229. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  2230. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  2231. {
  2232. ObjectInfo artInfo;
  2233. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  2234. artInfo.maxPerZone = 1;
  2235. artInfo.value = 2000; //treasure art
  2236. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  2237. artInfo.generateObject = [id]() -> CGObjectInstance *
  2238. {
  2239. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  2240. return handler->create(handler->getTemplates().front());
  2241. };
  2242. return artInfo;
  2243. };
  2244. for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  2245. {
  2246. auto creature = creatures[i];
  2247. int creaturesAmount = creatureToCount(creature);
  2248. if (!creaturesAmount)
  2249. continue;
  2250. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2251. oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2252. {
  2253. auto obj = new CGSeerHut();
  2254. obj->ID = Obj::SEER_HUT;
  2255. obj->subID = randomAppearance;
  2256. obj->rewardType = CGSeerHut::CREATURE;
  2257. obj->rID = creature->idNumber;
  2258. obj->rVal = creaturesAmount;
  2259. obj->quest->missionType = CQuest::MISSION_ART;
  2260. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2261. obj->quest->m5arts.push_back(artid);
  2262. gen->banQuestArt(artid);
  2263. gen->map->addQuest(obj);
  2264. this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
  2265. return obj;
  2266. };
  2267. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2268. oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
  2269. oi.probability = 3;
  2270. possibleObjects.push_back(oi);
  2271. }
  2272. static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
  2273. static int seerValues[] = { 2000, 5333, 8666, 12000 };
  2274. for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
  2275. {
  2276. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2277. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2278. oi.value = seerValues[i];
  2279. oi.probability = 10;
  2280. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2281. {
  2282. auto obj = new CGSeerHut();
  2283. obj->ID = Obj::SEER_HUT;
  2284. obj->subID = randomAppearance;
  2285. obj->rewardType = CGSeerHut::EXPERIENCE;
  2286. obj->rID = 0; //unitialized?
  2287. obj->rVal = seerExpGold[i];
  2288. obj->quest->missionType = CQuest::MISSION_ART;
  2289. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2290. obj->quest->m5arts.push_back(artid);
  2291. gen->banQuestArt(artid);
  2292. gen->map->addQuest(obj);
  2293. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2294. return obj;
  2295. };
  2296. possibleObjects.push_back(oi);
  2297. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2298. {
  2299. auto obj = new CGSeerHut();
  2300. obj->ID = Obj::SEER_HUT;
  2301. obj->subID = randomAppearance;
  2302. obj->rewardType = CGSeerHut::RESOURCES;
  2303. obj->rID = Res::GOLD;
  2304. obj->rVal = seerExpGold[i];
  2305. obj->quest->missionType = CQuest::MISSION_ART;
  2306. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2307. obj->quest->m5arts.push_back(artid);
  2308. gen->banQuestArt(artid);
  2309. gen->map->addQuest(obj);
  2310. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2311. return obj;
  2312. };
  2313. possibleObjects.push_back(oi);
  2314. }
  2315. }
  2316. }
  2317. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2318. {
  2319. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  2320. }