CRmgTemplateZone.cpp 82 KB

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