CRmgTemplateZone.cpp 77 KB

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