CRmgTemplateZone.cpp 76 KB

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