CRmgTemplateZone.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254
  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 "../CSpellHandler.h" //for choosing random spells
  18. #include "../mapObjects/CommonConstructors.h"
  19. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  20. #include "../mapObjects/CGPandoraBox.h"
  21. #include "../mapObjects/CRewardableObject.h"
  22. class CMap;
  23. class CMapEditManager;
  24. //class CGObjectInstance;
  25. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  26. {
  27. }
  28. int CRmgTemplateZone::CTownInfo::getTownCount() const
  29. {
  30. return townCount;
  31. }
  32. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  33. {
  34. if(value < 0)
  35. throw rmgException("Negative value for town count not allowed.");
  36. townCount = value;
  37. }
  38. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  39. {
  40. return castleCount;
  41. }
  42. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  43. {
  44. if(value < 0)
  45. throw rmgException("Negative value for castle count not allowed.");
  46. castleCount = value;
  47. }
  48. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  49. {
  50. return townDensity;
  51. }
  52. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  53. {
  54. if(value < 0)
  55. throw rmgException("Negative value for town density not allowed.");
  56. townDensity = value;
  57. }
  58. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  59. {
  60. return castleDensity;
  61. }
  62. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  63. {
  64. if(value < 0)
  65. throw rmgException("Negative value for castle density not allowed.");
  66. castleDensity = value;
  67. }
  68. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  69. {
  70. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  71. }
  72. float CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(float value)
  77. {
  78. nearestObjectDistance = std::max<float>(0, value); //never negative (or unitialized)
  79. }
  80. bool CTileInfo::shouldBeBlocked() const
  81. {
  82. return occupied == ETileType::BLOCKED;
  83. }
  84. bool CTileInfo::isBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  87. }
  88. bool CTileInfo::isPossible() const
  89. {
  90. return occupied == ETileType::POSSIBLE;
  91. }
  92. bool CTileInfo::isFree() const
  93. {
  94. return occupied == ETileType::FREE;
  95. }
  96. bool CTileInfo::isUsed() const
  97. {
  98. return occupied == ETileType::USED;
  99. }
  100. void CTileInfo::setOccupied(ETileType::ETileType value)
  101. {
  102. occupied = value;
  103. }
  104. ETileType::ETileType CTileInfo::getTileType() const
  105. {
  106. return occupied;
  107. }
  108. ETerrainType CTileInfo::getTerrainType() const
  109. {
  110. return terrain;
  111. }
  112. void CTileInfo::setTerrainType(ETerrainType value)
  113. {
  114. terrain = value;
  115. }
  116. CRmgTemplateZone::CRmgTemplateZone() :
  117. id(0),
  118. type(ETemplateZoneType::PLAYER_START),
  119. size(1),
  120. townsAreSameType(false),
  121. matchTerrainToTown(true),
  122. townType(ETownType::NEUTRAL),
  123. terrainType (ETerrainType::GRASS),
  124. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  125. minGuardedValue(0)
  126. {
  127. terrainTypes = getDefaultTerrainTypes();
  128. }
  129. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  130. {
  131. return id;
  132. }
  133. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  134. {
  135. if(value <= 0)
  136. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  137. id = value;
  138. }
  139. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  140. {
  141. return type;
  142. }
  143. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  144. {
  145. type = value;
  146. }
  147. int CRmgTemplateZone::getSize() const
  148. {
  149. return size;
  150. }
  151. void CRmgTemplateZone::setSize(int value)
  152. {
  153. if(value <= 0)
  154. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  155. size = value;
  156. }
  157. boost::optional<int> CRmgTemplateZone::getOwner() const
  158. {
  159. return owner;
  160. }
  161. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  162. {
  163. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  164. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  165. owner = value;
  166. }
  167. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  168. {
  169. return playerTowns;
  170. }
  171. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  172. {
  173. playerTowns = value;
  174. }
  175. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  176. {
  177. return neutralTowns;
  178. }
  179. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  180. {
  181. neutralTowns = value;
  182. }
  183. bool CRmgTemplateZone::getTownsAreSameType() const
  184. {
  185. return townsAreSameType;
  186. }
  187. void CRmgTemplateZone::setTownsAreSameType(bool value)
  188. {
  189. townsAreSameType = value;
  190. }
  191. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  192. {
  193. return townTypes;
  194. }
  195. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  196. {
  197. townTypes = value;
  198. }
  199. void CRmgTemplateZone::setMonsterTypes(const std::set<TFaction> & value)
  200. {
  201. monsterTypes = value;
  202. }
  203. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  204. {
  205. std::set<TFaction> defaultTowns;
  206. auto towns = VLC->townh->getDefaultAllowed();
  207. for(int i = 0; i < towns.size(); ++i)
  208. {
  209. if(towns[i]) defaultTowns.insert(i);
  210. }
  211. return defaultTowns;
  212. }
  213. bool CRmgTemplateZone::getMatchTerrainToTown() const
  214. {
  215. return matchTerrainToTown;
  216. }
  217. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  218. {
  219. matchTerrainToTown = value;
  220. }
  221. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  222. {
  223. return terrainTypes;
  224. }
  225. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  226. {
  227. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  228. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  229. terrainTypes = value;
  230. }
  231. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  232. {
  233. std::set<ETerrainType> terTypes;
  234. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  235. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  236. for (auto & allowedTerType : allowedTerTypes)
  237. terTypes.insert(allowedTerType);
  238. return terTypes;
  239. }
  240. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  241. {
  242. mines[res] = amount;
  243. }
  244. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  245. {
  246. return mines;
  247. }
  248. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  249. {
  250. connections.push_back (otherZone);
  251. }
  252. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  253. {
  254. return connections;
  255. }
  256. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  257. {
  258. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  259. zoneMonsterStrength = val;
  260. }
  261. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  262. {
  263. treasureInfo.push_back(info);
  264. }
  265. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  266. {
  267. return treasureInfo;
  268. }
  269. std::set<int3>* CRmgTemplateZone::getFreePaths()
  270. {
  271. return &freePaths;
  272. }
  273. float3 CRmgTemplateZone::getCenter() const
  274. {
  275. return center;
  276. }
  277. void CRmgTemplateZone::setCenter(const float3 &f)
  278. {
  279. //limit boundaries to (0,1) square
  280. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  281. }
  282. bool CRmgTemplateZone::pointIsIn(int x, int y)
  283. {
  284. return true;
  285. }
  286. int3 CRmgTemplateZone::getPos() const
  287. {
  288. return pos;
  289. }
  290. void CRmgTemplateZone::setPos(const int3 &Pos)
  291. {
  292. pos = Pos;
  293. }
  294. void CRmgTemplateZone::addTile (const int3 &pos)
  295. {
  296. tileinfo.insert(pos);
  297. }
  298. std::set<int3> CRmgTemplateZone::getTileInfo () const
  299. {
  300. return tileinfo;
  301. }
  302. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  303. {
  304. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  305. //for (auto tile : tileinfo)
  306. //{
  307. // if (tile.dist2d(this->pos) > distance)
  308. // {
  309. // gen->setOccupied(tile, ETileType::USED);
  310. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  311. // }
  312. //}
  313. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  314. {
  315. return tile.dist2d(this->pos) > distance;
  316. });
  317. }
  318. void CRmgTemplateZone::clearTiles()
  319. {
  320. tileinfo.clear();
  321. }
  322. void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
  323. {
  324. vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
  325. {
  326. return gen->isPossible(tile);
  327. });
  328. }
  329. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  330. {
  331. for (auto tile : tileinfo)
  332. {
  333. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  334. {
  335. if (!vstd::contains(this->tileinfo, pos))
  336. {
  337. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  338. {
  339. if (gen->isPossible(pos))
  340. gen->setOccupied (pos, ETileType::BLOCKED);
  341. });
  342. }
  343. });
  344. }
  345. }
  346. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  347. {
  348. for (auto tile : tileinfo)
  349. {
  350. if (gen->isFree(tile))
  351. freePaths.insert(tile);
  352. }
  353. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  354. std::set<int3> possibleTiles;
  355. std::set<int3> tilesToClear; //will be set clear
  356. std::set<int3> tilesToIgnore; //will be erased in this iteration
  357. //the more treasure density, the greater distance between paths. Scaling is experimental.
  358. int totalDensity = 0;
  359. for (auto ti : treasureInfo)
  360. totalDensity =+ ti.density;
  361. const float minDistance = 10 * 10; //squared
  362. for (auto tile : tileinfo)
  363. {
  364. if (gen->isFree(tile))
  365. clearedTiles.push_back(tile);
  366. else if (gen->isPossible(tile))
  367. possibleTiles.insert(tile);
  368. }
  369. assert (clearedTiles.size()); //this should come from zone connections
  370. if (type != ETemplateZoneType::JUNCTION)
  371. {
  372. //junction is not fractalized, has only one straight path
  373. //everything else remains blocked
  374. while (possibleTiles.size())
  375. {
  376. //link tiles in random order
  377. std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
  378. RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
  379. for (auto tileToMakePath : tilesToMakePath)
  380. {
  381. //find closest free tile
  382. float currentDistance = 1e10;
  383. int3 closestTile(-1, -1, -1);
  384. for (auto clearTile : clearedTiles)
  385. {
  386. float distance = tileToMakePath.dist2dSQ(clearTile);
  387. if (distance < currentDistance)
  388. {
  389. currentDistance = distance;
  390. closestTile = clearTile;
  391. }
  392. if (currentDistance <= minDistance)
  393. {
  394. //this tile is close enough. Forget about it and check next one
  395. tilesToIgnore.insert(tileToMakePath);
  396. break;
  397. }
  398. }
  399. //if tiles is not close enough, make path to it
  400. if (currentDistance > minDistance)
  401. {
  402. crunchPath(gen, tileToMakePath, closestTile, id, &tilesToClear);
  403. break; //next iteration - use already cleared tiles
  404. }
  405. }
  406. for (auto tileToClear : tilesToClear)
  407. {
  408. //move cleared tiles from one set to another
  409. clearedTiles.push_back(tileToClear);
  410. vstd::erase_if_present(possibleTiles, tileToClear);
  411. }
  412. for (auto tileToClear : tilesToIgnore)
  413. {
  414. //these tiles are already connected, ignore them
  415. vstd::erase_if_present(possibleTiles, tileToClear);
  416. }
  417. if (tilesToClear.empty()) //nothing else can be done (?)
  418. break;
  419. tilesToClear.clear(); //empty this container
  420. tilesToIgnore.clear();
  421. }
  422. }
  423. for (auto tile : clearedTiles)
  424. {
  425. freePaths.insert(tile);
  426. }
  427. //now block most distant tiles away from passages
  428. float blockDistance = minDistance * 0.25f;
  429. for (auto tile : tileinfo)
  430. {
  431. if (!gen->isPossible(tile))
  432. continue;
  433. bool closeTileFound = false;
  434. for (auto clearTile : freePaths)
  435. {
  436. float distance = tile.dist2dSQ(clearTile);
  437. if (distance < blockDistance)
  438. {
  439. closeTileFound = true;
  440. break;
  441. }
  442. }
  443. if (!closeTileFound) //this tile is far enough from passages
  444. gen->setOccupied(tile, ETileType::BLOCKED);
  445. }
  446. #define PRINT_FRACTALIZED_MAP false
  447. if (PRINT_FRACTALIZED_MAP) //enable to debug
  448. {
  449. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  450. int levels = gen->map->twoLevel ? 2 : 1;
  451. int width = gen->map->width;
  452. int height = gen->map->height;
  453. for (int k = 0; k < levels; k++)
  454. {
  455. for(int j=0; j<height; j++)
  456. {
  457. for (int i=0; i<width; i++)
  458. {
  459. char t = '?';
  460. switch (gen->getTile(int3(i, j, k)).getTileType())
  461. {
  462. case ETileType::FREE:
  463. t = ' '; break;
  464. case ETileType::BLOCKED:
  465. t = '#'; break;
  466. case ETileType::POSSIBLE:
  467. t = '-'; break;
  468. case ETileType::USED:
  469. t = 'O'; break;
  470. }
  471. out << t;
  472. }
  473. out << std::endl;
  474. }
  475. out << std::endl;
  476. }
  477. out << std::endl;
  478. }
  479. //logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  480. }
  481. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  482. {
  483. /*
  484. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  485. do not leave zone border
  486. */
  487. bool result = false;
  488. bool end = false;
  489. int3 currentPos = src;
  490. float distance = currentPos.dist2dSQ (dst);
  491. while (!end)
  492. {
  493. if (currentPos == dst)
  494. {
  495. result = true;
  496. break;
  497. }
  498. auto lastDistance = distance;
  499. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  500. {
  501. if (!result) //not sure if lambda is worth it...
  502. {
  503. if (pos == dst)
  504. {
  505. result = true;
  506. end = true;
  507. }
  508. if (pos.dist2dSQ (dst) < distance)
  509. {
  510. if (!gen->isBlocked(pos))
  511. {
  512. if (vstd::contains (tileinfo, pos))
  513. {
  514. if (gen->isPossible(pos))
  515. {
  516. gen->setOccupied (pos, ETileType::FREE);
  517. if (clearedTiles)
  518. clearedTiles->insert(pos);
  519. currentPos = pos;
  520. distance = currentPos.dist2dSQ (dst);
  521. }
  522. else if (gen->isFree(pos))
  523. {
  524. end = true;
  525. result = true;
  526. }
  527. }
  528. }
  529. }
  530. }
  531. });
  532. int3 anotherPos(-1, -1, -1);
  533. if (!(result || distance < lastDistance)) //we do not advance, use more advaced pathfinding algorithm?
  534. {
  535. //try any nearby tiles, even if its not closer than current
  536. float lastDistance = 2 * distance; //start with significantly larger value
  537. gen->foreach_neighbour(currentPos, [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  538. {
  539. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  540. {
  541. if (vstd::contains(tileinfo, pos))
  542. {
  543. if (gen->isPossible(pos))
  544. {
  545. if (clearedTiles)
  546. clearedTiles->insert(pos);
  547. anotherPos = pos;
  548. lastDistance = currentPos.dist2dSQ(dst);
  549. }
  550. }
  551. }
  552. });
  553. if (anotherPos.valid())
  554. {
  555. if (clearedTiles)
  556. clearedTiles->insert(anotherPos);
  557. gen->setOccupied(anotherPos, ETileType::FREE);
  558. currentPos = anotherPos;
  559. }
  560. }
  561. if (!(result || distance < lastDistance || anotherPos.valid()))
  562. {
  563. logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  564. break;
  565. }
  566. }
  567. return result;
  568. }
  569. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  570. {
  571. requiredObjects.push_back(std::make_pair(obj, strength));
  572. }
  573. void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
  574. {
  575. closeObjects.push_back(std::make_pair(obj, strength));
  576. }
  577. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  578. {
  579. //precalculate actual (randomized) monster strength based on this post
  580. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  581. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  582. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  583. static const int value1[] = {2500, 1500, 1000, 500, 0};
  584. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  585. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  586. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  587. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  588. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  589. strength = strength1 + strength2;
  590. if (strength < 2000)
  591. return false; //no guard at all
  592. CreatureID creId = CreatureID::NONE;
  593. int amount = 0;
  594. std::vector<CreatureID> possibleCreatures;
  595. for (auto cre : VLC->creh->creatures)
  596. {
  597. if (cre->special)
  598. continue;
  599. if (!vstd::contains(monsterTypes, cre->faction))
  600. continue;
  601. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between minimum size of given stack and 100
  602. {
  603. possibleCreatures.push_back(cre->idNumber);
  604. }
  605. }
  606. if (possibleCreatures.size())
  607. {
  608. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  609. amount = strength / VLC->creh->creatures[creId]->AIValue;
  610. if (amount >= 4)
  611. amount *= gen->rand.nextDouble(0.75, 1.25);
  612. }
  613. else //just pick any available creature
  614. {
  615. creId = CreatureID(132); //Azure Dragon
  616. amount = strength / VLC->creh->creatures[creId]->AIValue;
  617. }
  618. auto guard = new CGCreature();
  619. guard->ID = Obj::MONSTER;
  620. guard->subID = creId;
  621. guard->character = CGCreature::HOSTILE;
  622. auto hlp = new CStackInstance(creId, amount);
  623. //will be set during initialization
  624. guard->putStack(SlotID(0), hlp);
  625. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  626. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  627. placeObject(gen, guard, pos);
  628. if (clearSurroundingTiles)
  629. {
  630. //do not spawn anything near monster
  631. gen->foreach_neighbour (pos, [gen](int3 pos)
  632. {
  633. if (gen->isPossible(pos))
  634. gen->setOccupied(pos, ETileType::FREE);
  635. });
  636. }
  637. return true;
  638. }
  639. bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  640. {
  641. CTreasurePileInfo info;
  642. std::map<int3, CGObjectInstance *> treasures;
  643. std::set<int3> boundary;
  644. int3 guardPos (-1,-1,-1);
  645. info.nextTreasurePos = pos;
  646. int maxValue = treasureInfo.max;
  647. int minValue = treasureInfo.min;
  648. ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
  649. int currentValue = 0;
  650. CGObjectInstance * object = nullptr;
  651. while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable
  652. {
  653. treasures[info.nextTreasurePos] = nullptr;
  654. for (auto treasurePos : treasures)
  655. {
  656. gen->foreach_neighbour(treasurePos.first, [gen, &boundary](int3 pos)
  657. {
  658. boundary.insert(pos);
  659. });
  660. }
  661. for (auto treasurePos : treasures)
  662. {
  663. //leaving only boundary around objects
  664. vstd::erase_if_present(boundary, treasurePos.first);
  665. }
  666. for (auto tile : boundary)
  667. {
  668. //we can't extend boundary anymore
  669. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  670. break;
  671. }
  672. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  673. if (!oi.value) //0 value indicates no object
  674. {
  675. vstd::erase_if_present(treasures, info.nextTreasurePos);
  676. break;
  677. }
  678. else
  679. {
  680. object = oi.generateObject();
  681. //remove from possible objects
  682. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  683. assert (oiptr != possibleObjects.end());
  684. oiptr->maxPerZone--;
  685. if (!oiptr->maxPerZone)
  686. possibleObjects.erase(oiptr);
  687. //TODO
  688. //update treasure pile area
  689. int3 visitablePos = info.nextTreasurePos;
  690. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  691. if (oi.templ.isVisitableFromTop())
  692. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  693. else
  694. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  695. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  696. {
  697. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  698. info.occupiedPositions.insert(blockPos);
  699. info.blockedPositions.insert(blockPos);
  700. }
  701. info.occupiedPositions.insert(visitablePos);
  702. currentValue += oi.value;
  703. treasures[info.nextTreasurePos] = object;
  704. //now find place for next object
  705. int3 placeFound(-1,-1,-1);
  706. //randomize next position from among possible ones
  707. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  708. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  709. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  710. {
  711. return lhs.y < rhs.y;
  712. };
  713. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  714. for (auto tile : boundaryCopy)
  715. {
  716. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  717. {
  718. bool here = true;
  719. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  720. {
  721. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  722. here = false;
  723. });
  724. if (here)
  725. {
  726. placeFound = tile;
  727. break;
  728. }
  729. }
  730. }
  731. if (placeFound.valid())
  732. info.nextTreasurePos = placeFound;
  733. else
  734. break; //no more place to add any objects
  735. }
  736. }
  737. if (treasures.size())
  738. {
  739. //find object closest to zone center, then connect it to the middle of the zone
  740. int3 closestFreeTile (-1,-1,-1);
  741. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  742. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  743. else
  744. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  745. int3 closestTile = int3(-1,-1,-1);
  746. float minDistance = 1e10;
  747. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  748. {
  749. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  750. {
  751. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  752. minDistance = closestFreeTile.dist2d(visitablePos);
  753. }
  754. }
  755. if (!closestTile.valid())
  756. {
  757. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  758. {
  759. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  760. {
  761. closestTile = visitablePos;
  762. minDistance = closestFreeTile.dist2d(visitablePos);
  763. }
  764. }
  765. }
  766. assert (closestTile.valid());
  767. for (auto tile : info.occupiedPositions)
  768. {
  769. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  770. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  771. }
  772. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  773. {
  774. //we can't connect this pile, just block it off and start over
  775. for (auto treasure : treasures)
  776. {
  777. if (gen->isPossible(treasure.first))
  778. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  779. }
  780. return true;
  781. }
  782. //update boundary around our objects, including knowledge about objects visitable from bottom
  783. boundary.clear();
  784. for (auto tile : info.visitableFromBottomPositions)
  785. {
  786. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  787. {
  788. if (pos.y >= tile.y) //don't block these objects from above
  789. boundary.insert(pos);
  790. });
  791. }
  792. for (auto tile : info.visitableFromTopPositions)
  793. {
  794. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  795. {
  796. boundary.insert(pos);
  797. });
  798. }
  799. bool isPileGuarded = currentValue >= minGuardedValue;
  800. for (auto tile : boundary) //guard must be standing there
  801. {
  802. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  803. {
  804. guardPos = tile;
  805. break;
  806. }
  807. }
  808. if (guardPos.valid())
  809. {
  810. for (auto treasure : treasures)
  811. {
  812. int3 visitableOffset = treasure.second->getVisitableOffset();
  813. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  814. }
  815. if (addMonster(gen, guardPos, currentValue, false))
  816. {//block only if the object is guarded
  817. for (auto tile : boundary)
  818. {
  819. if (gen->isPossible(tile))
  820. gen->setOccupied(tile, ETileType::BLOCKED);
  821. }
  822. //do not spawn anything near monster
  823. gen->foreach_neighbour(guardPos, [gen](int3 pos)
  824. {
  825. if (gen->isPossible(pos))
  826. gen->setOccupied(pos, ETileType::FREE);
  827. });
  828. }
  829. else //mo monster in this pile, make some free space (needed?)
  830. {
  831. for (auto tile : boundary)
  832. if (gen->isPossible(tile))
  833. gen->setOccupied(tile, ETileType::FREE);
  834. }
  835. }
  836. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  837. {
  838. for (auto treasure : treasures)
  839. {
  840. if (gen->isPossible(treasure.first))
  841. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  842. delete treasure.second;
  843. }
  844. }
  845. return true;
  846. }
  847. else //we did not place eveyrthing successfully
  848. return false;
  849. }
  850. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  851. {
  852. //FIXME: handle case that this player is not present -> towns should be set to neutral
  853. int totalTowns = 0;
  854. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  855. {
  856. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  857. for (auto tile : town->getBlockedPos())
  858. {
  859. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  860. {
  861. if (gen->isPossible(pos))
  862. {
  863. gen->setOccupied(pos, ETileType::FREE);
  864. }
  865. });
  866. }
  867. };
  868. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  869. {
  870. for (int i = 0; i < count; i++)
  871. {
  872. auto town = new CGTownInstance();
  873. town->ID = Obj::TOWN;
  874. if (this->townsAreSameType)
  875. town->subID = townType;
  876. else
  877. {
  878. if (townTypes.size())
  879. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  880. else
  881. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  882. }
  883. town->tempOwner = player;
  884. if (hasFort)
  885. town->builtBuildings.insert(BuildingID::FORT);
  886. town->builtBuildings.insert(BuildingID::DEFAULT);
  887. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  888. {
  889. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  890. town->possibleSpells.push_back(spell->id);
  891. }
  892. if (!totalTowns)
  893. {
  894. //first town in zone sets the facton of entire zone
  895. town->subID = townType;
  896. //register MAIN town of zone
  897. gen->registerZone(town->subID);
  898. //first town in zone goes in the middle
  899. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  900. cutPathAroundTown(town);
  901. }
  902. else
  903. addRequiredObject (town);
  904. totalTowns++;
  905. }
  906. };
  907. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  908. {
  909. //set zone types to player faction, generate main town
  910. logGlobal->infoStream() << "Preparing playing zone";
  911. int player_id = *owner - 1;
  912. auto & playerInfo = gen->map->players[player_id];
  913. if (playerInfo.canAnyonePlay())
  914. {
  915. PlayerColor player(player_id);
  916. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  917. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  918. {
  919. if (townTypes.size())
  920. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  921. else
  922. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  923. }
  924. auto town = new CGTownInstance();
  925. town->ID = Obj::TOWN;
  926. town->subID = townType;
  927. town->tempOwner = player;
  928. town->builtBuildings.insert(BuildingID::FORT);
  929. town->builtBuildings.insert(BuildingID::DEFAULT);
  930. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  931. {
  932. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  933. town->possibleSpells.push_back(spell->id);
  934. }
  935. //towns are big objects and should be centered around visitable position
  936. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  937. cutPathAroundTown(town);
  938. totalTowns++;
  939. //register MAIN town of zone only
  940. gen->registerZone (town->subID);
  941. logGlobal->traceStream() << "Fill player info " << player_id;
  942. // Update player info
  943. playerInfo.allowedFactions.clear();
  944. playerInfo.allowedFactions.insert (townType);
  945. playerInfo.hasMainTown = true;
  946. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  947. playerInfo.generateHeroAtMainTown = true;
  948. //now create actual towns
  949. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  950. addNewTowns (playerTowns.getTownCount(), false, player);
  951. //requiredObjects.push_back(town);
  952. }
  953. else
  954. {
  955. type = ETemplateZoneType::TREASURE;
  956. if (townTypes.size())
  957. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  958. else
  959. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  960. }
  961. }
  962. else //no player
  963. {
  964. if (townTypes.size())
  965. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  966. else
  967. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  968. }
  969. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  970. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  971. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  972. {
  973. //25% chance for neutral
  974. if (gen->rand.nextInt(1, 100) <= 25)
  975. {
  976. townType = ETownType::NEUTRAL;
  977. }
  978. else
  979. {
  980. if (townTypes.size())
  981. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  982. else if (monsterTypes.size())
  983. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  984. }
  985. }
  986. }
  987. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  988. {
  989. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  990. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  991. else
  992. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  993. //TODO: allow new types of terrain?
  994. if (pos.z)
  995. {
  996. if (terrainType != ETerrainType::LAVA)
  997. terrainType = ETerrainType::SUBTERRANEAN;
  998. }
  999. else
  1000. {
  1001. if (terrainType == ETerrainType::SUBTERRANEAN)
  1002. terrainType = ETerrainType::DIRT;
  1003. }
  1004. paintZoneTerrain (gen, terrainType);
  1005. }
  1006. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  1007. {
  1008. std::vector<int3> tiles;
  1009. for (auto tile : tileinfo)
  1010. {
  1011. tiles.push_back (tile);
  1012. }
  1013. gen->editManager->getTerrainSelection().setSelection(tiles);
  1014. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1015. }
  1016. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  1017. {
  1018. std::vector<Res::ERes> required_mines;
  1019. required_mines.push_back(Res::ERes::WOOD);
  1020. required_mines.push_back(Res::ERes::ORE);
  1021. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1022. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1023. for (const auto & res : woodOre)
  1024. {
  1025. for (int i = 0; i < mines[res]; i++)
  1026. {
  1027. auto mine = new CGMine();
  1028. mine->ID = Obj::MINE;
  1029. mine->subID = static_cast<si32>(res);
  1030. mine->producedResource = res;
  1031. mine->producedQuantity = mine->defaultResProduction();
  1032. addCloseObject(mine, 1500);
  1033. }
  1034. }
  1035. for (const auto & res : preciousResources)
  1036. {
  1037. for (int i = 0; i < mines[res]; i++)
  1038. {
  1039. auto mine = new CGMine();
  1040. mine->ID = Obj::MINE;
  1041. mine->subID = static_cast<si32>(res);
  1042. mine->producedResource = res;
  1043. mine->producedQuantity = mine->defaultResProduction();
  1044. addRequiredObject(mine, 3500);
  1045. }
  1046. }
  1047. for (int i = 0; i < mines[Res::GOLD]; i++)
  1048. {
  1049. auto mine = new CGMine();
  1050. mine->ID = Obj::MINE;
  1051. mine->subID = static_cast<si32>(Res::GOLD);
  1052. mine->producedResource = Res::GOLD;
  1053. mine->producedQuantity = mine->defaultResProduction();
  1054. addRequiredObject(mine, 7000);
  1055. }
  1056. return true;
  1057. }
  1058. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1059. {
  1060. logGlobal->traceStream() << "Creating required objects";
  1061. for(const auto &obj : requiredObjects)
  1062. {
  1063. int3 pos;
  1064. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  1065. {
  1066. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  1067. //TODO CLEANUP!
  1068. return false;
  1069. }
  1070. placeObject (gen, obj.first, pos);
  1071. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1072. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1073. }
  1074. for (const auto &obj : closeObjects)
  1075. {
  1076. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1077. // smallest distance to zone center, greatest distance to nearest object
  1078. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1079. {
  1080. return (this->pos.dist2dSQ(lhs) * 0.5f - gen->getNearestObjectDistance(lhs)) < (this->pos.dist2dSQ(rhs) * 0.5f - gen->getNearestObjectDistance(rhs));
  1081. };
  1082. boost::sort (tiles, isCloser);
  1083. setTemplateForObject(gen, obj.first);
  1084. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1085. bool result = false;
  1086. for (auto tile : tiles)
  1087. {
  1088. //object must be accessible from at least one surounding tile
  1089. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile, tilesBlockedByObject))
  1090. continue;
  1091. //avoid borders
  1092. if (gen->isPossible(tile))
  1093. {
  1094. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1095. {
  1096. placeObject(gen, obj.first, tile);
  1097. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1098. result = true;
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. if (!result)
  1104. {
  1105. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1106. //TODO CLEANUP!
  1107. return false;
  1108. }
  1109. }
  1110. return true;
  1111. }
  1112. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1113. {
  1114. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  1115. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1116. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1117. minGuardedValue = minGuardedValues[monsterStrength];
  1118. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1119. {
  1120. return lhs.max > rhs.max;
  1121. };
  1122. //place biggest treasures first at large distance, place smaller ones inbetween
  1123. boost::sort(treasureInfo, valueComparator);
  1124. int totalDensity = 0;
  1125. for (auto t : treasureInfo)
  1126. {
  1127. totalDensity += t.density;
  1128. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1129. //also, normalize it to zone count - higher count means relatively smaller zones
  1130. //this is squared distance for optimization purposes
  1131. const double minDistance = std::max<float>((125.f / totalDensity), 2);
  1132. //distance lower than 2 causes objects to overlap and crash
  1133. do {
  1134. //optimization - don't check tiles which are not allowed
  1135. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1136. {
  1137. return !gen->isPossible(tile);
  1138. });
  1139. int3 pos;
  1140. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1141. if (!findPlaceForTreasurePile(gen, minDistance, pos, t.min))
  1142. {
  1143. break;
  1144. }
  1145. createTreasurePile(gen, pos, minDistance, t);
  1146. } while (true);
  1147. }
  1148. }
  1149. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1150. {
  1151. //tighten obstacles to improve visuals
  1152. for (int i = 0; i < 3; ++i)
  1153. {
  1154. int blockedTiles = 0;
  1155. int freeTiles = 0;
  1156. for (auto tile : tileinfo)
  1157. {
  1158. if (!gen->isPossible(tile)) //only possible tiles can change
  1159. continue;
  1160. int blockedNeighbours = 0;
  1161. int freeNeighbours = 0;
  1162. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1163. {
  1164. if (gen->isBlocked(pos))
  1165. blockedNeighbours++;
  1166. if (gen->isFree(pos))
  1167. freeNeighbours++;
  1168. });
  1169. if (blockedNeighbours > 4)
  1170. {
  1171. gen->setOccupied(tile, ETileType::BLOCKED);
  1172. blockedTiles++;
  1173. }
  1174. else if (freeNeighbours > 4)
  1175. {
  1176. gen->setOccupied(tile, ETileType::FREE);
  1177. freeTiles++;
  1178. }
  1179. }
  1180. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1181. }
  1182. #define MAKE_COOL_UNDERGROUND_TUNNELS false
  1183. if (pos.z && MAKE_COOL_UNDERGROUND_TUNNELS) //underground
  1184. {
  1185. std::vector<int3> rockTiles;
  1186. for (auto tile : tileinfo)
  1187. {
  1188. if (gen->shouldBeBlocked(tile))
  1189. {
  1190. bool placeRock = true;
  1191. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1192. {
  1193. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1194. placeRock = false;
  1195. });
  1196. if (placeRock)
  1197. {
  1198. rockTiles.push_back(tile);
  1199. }
  1200. }
  1201. }
  1202. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1203. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1204. for (auto tile : rockTiles)
  1205. {
  1206. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1207. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1208. //{
  1209. // if (!gen->isUsed(pos))
  1210. // gen->setOccupied (pos, ETileType::BLOCKED);
  1211. //});
  1212. }
  1213. }
  1214. typedef std::vector<ObjectTemplate> obstacleVector;
  1215. //obstacleVector possibleObstacles;
  1216. std::map <ui8, obstacleVector> obstaclesBySize;
  1217. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1218. std::vector<obstaclePair> possibleObstacles;
  1219. //get all possible obstacles for this terrain
  1220. for (auto primaryID : VLC->objtypeh->knownObjects())
  1221. {
  1222. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1223. {
  1224. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1225. if (handler->isStaticObject())
  1226. {
  1227. for (auto temp : handler->getTemplates())
  1228. {
  1229. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1230. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1231. }
  1232. }
  1233. }
  1234. }
  1235. for (auto o : obstaclesBySize)
  1236. {
  1237. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1238. }
  1239. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1240. {
  1241. return p1.first > p2.first; //bigger obstacles first
  1242. });
  1243. auto sel = gen->editManager->getTerrainSelection();
  1244. sel.clearSelection();
  1245. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1246. {
  1247. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1248. int3 obstaclePos = tile - temp.getBlockMapOffset();
  1249. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1250. {
  1251. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1252. placeObject(gen, obj, obstaclePos, false);
  1253. return true;
  1254. }
  1255. return false;
  1256. };
  1257. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1258. for (auto tile : boost::adaptors::reverse(tileinfo))
  1259. {
  1260. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1261. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1262. {
  1263. //start from biggets obstacles
  1264. for (int i = 0; i < possibleObstacles.size(); i++)
  1265. {
  1266. if (tryToPlaceObstacleHere(tile, i))
  1267. break;
  1268. }
  1269. }
  1270. }
  1271. }
  1272. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1273. {
  1274. initTerrainType(gen);
  1275. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1276. addAllPossibleObjects (gen);
  1277. placeMines(gen);
  1278. createRequiredObjects(gen);
  1279. fractalize(gen); //after required objects are created and linked with their own paths
  1280. createTreasures(gen);
  1281. createObstacles(gen);
  1282. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1283. return true;
  1284. }
  1285. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1286. {
  1287. float best_distance = 0;
  1288. bool result = false;
  1289. bool needsGuard = value > minGuardedValue;
  1290. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1291. for(auto tile : possibleTiles)
  1292. {
  1293. auto dist = gen->getNearestObjectDistance(tile);
  1294. if ((dist >= min_dist) && (dist > best_distance))
  1295. {
  1296. bool allTilesAvailable = true;
  1297. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1298. {
  1299. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1300. {
  1301. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1302. }
  1303. });
  1304. if (allTilesAvailable)
  1305. {
  1306. best_distance = dist;
  1307. pos = tile;
  1308. result = true;
  1309. }
  1310. }
  1311. }
  1312. if (result)
  1313. {
  1314. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1315. }
  1316. return result;
  1317. }
  1318. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1319. {
  1320. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1321. return false;
  1322. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1323. for (auto blockingTile : tilesBlockedByObject)
  1324. {
  1325. int3 t = pos + blockingTile;
  1326. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1327. {
  1328. return false; //if at least one tile is not possible, object can't be placed here
  1329. }
  1330. }
  1331. return true;
  1332. }
  1333. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1334. {
  1335. bool accessible = false;
  1336. for (int x = -1; x < 2; x++)
  1337. {
  1338. for (int y = -1; y <2; y++)
  1339. {
  1340. if (x && y) //check only if object is visitable from another tile
  1341. {
  1342. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1343. if (!vstd::contains(tilesBlockedByObject, offset))
  1344. {
  1345. int3 nearbyPos = tile + offset;
  1346. if (gen->map->isInTheMap(nearbyPos))
  1347. {
  1348. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1349. accessible = true;
  1350. }
  1351. }
  1352. }
  1353. };
  1354. }
  1355. return accessible;
  1356. }
  1357. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1358. {
  1359. if (obj->appearance.id == Obj::NO_OBJ)
  1360. {
  1361. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1362. if (templates.empty())
  1363. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1364. obj->appearance = templates.front();
  1365. }
  1366. }
  1367. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1368. {
  1369. for (auto blockingTile : tilesBlockedByObject)
  1370. {
  1371. int3 t = tile + blockingTile;
  1372. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1373. {
  1374. //if at least one tile is not possible, object can't be placed here
  1375. return false;
  1376. }
  1377. }
  1378. return true;
  1379. }
  1380. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1381. {
  1382. //we need object apperance to deduce free tile
  1383. setTemplateForObject(gen, obj);
  1384. //si32 min_dist = sqrt(tileinfo.size()/density);
  1385. int best_distance = 0;
  1386. bool result = false;
  1387. //si32 w = gen->map->width;
  1388. //si32 h = gen->map->height;
  1389. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1390. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1391. for (auto tile : tileinfo)
  1392. {
  1393. //object must be accessible from at least one surounding tile
  1394. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1395. continue;
  1396. auto ti = gen->getTile(tile);
  1397. auto dist = ti.getNearestObjectDistance();
  1398. //avoid borders
  1399. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1400. {
  1401. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1402. {
  1403. best_distance = dist;
  1404. pos = tile;
  1405. result = true;
  1406. }
  1407. }
  1408. }
  1409. if (result)
  1410. {
  1411. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1412. }
  1413. return result;
  1414. }
  1415. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1416. {
  1417. if (!gen->map->isInTheMap(pos))
  1418. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1419. object->pos = pos;
  1420. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1421. throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
  1422. for (auto tile : object->getBlockedPos())
  1423. {
  1424. if (!gen->map->isInTheMap(tile))
  1425. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1426. }
  1427. if (object->appearance.id == Obj::NO_OBJ)
  1428. {
  1429. auto terrainType = gen->map->getTile(pos).terType;
  1430. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1431. if (templates.empty())
  1432. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
  1433. object->appearance = templates.front();
  1434. }
  1435. gen->editManager->insertObject(object, pos);
  1436. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1437. }
  1438. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1439. {
  1440. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1441. checkAndPlaceObject (gen, object, pos);
  1442. auto points = object->getBlockedPos();
  1443. if (object->isVisitable())
  1444. points.insert(pos + object->getVisitableOffset());
  1445. points.insert(pos);
  1446. for(auto p : points)
  1447. {
  1448. if (gen->map->isInTheMap(p))
  1449. {
  1450. gen->setOccupied(p, ETileType::USED);
  1451. }
  1452. }
  1453. if (updateDistance)
  1454. {
  1455. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1456. {
  1457. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1458. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1459. }
  1460. }
  1461. }
  1462. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1463. {
  1464. placeObject(gen, object, pos);
  1465. guardObject(gen, object, str, zoneGuard);
  1466. }
  1467. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1468. {
  1469. //get all tiles from which this object can be accessed
  1470. int3 visitable = object->visitablePos();
  1471. std::vector<int3> tiles;
  1472. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1473. gen->foreach_neighbour(visitable, [&](int3& pos)
  1474. {
  1475. if (gen->isPossible(pos))
  1476. {
  1477. if (!vstd::contains(tilesBlockedByObject, pos))
  1478. {
  1479. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1480. {
  1481. tiles.push_back(pos);
  1482. }
  1483. }
  1484. };
  1485. });
  1486. return tiles;
  1487. }
  1488. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1489. {
  1490. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1491. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1492. int3 guardTile(-1,-1,-1);
  1493. for (auto tile : tiles)
  1494. {
  1495. //crunching path may fail if center of the zone is directly over wide object
  1496. //make sure object is accessible before surrounding it with blocked tiles
  1497. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1498. {
  1499. guardTile = tile;
  1500. break;
  1501. }
  1502. }
  1503. if (!guardTile.valid())
  1504. {
  1505. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1506. return false;
  1507. }
  1508. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1509. {
  1510. for (auto pos : tiles)
  1511. {
  1512. if (!gen->isFree(pos))
  1513. gen->setOccupied(pos, ETileType::BLOCKED);
  1514. }
  1515. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1516. {
  1517. if (gen->isPossible(pos))
  1518. gen->setOccupied (pos, ETileType::FREE);
  1519. });
  1520. gen->setOccupied (guardTile, ETileType::USED);
  1521. }
  1522. else //allow no guard or other object in front of this object
  1523. {
  1524. for (auto tile : tiles)
  1525. if (gen->isPossible(tile))
  1526. gen->setOccupied (tile, ETileType::FREE);
  1527. }
  1528. return true;
  1529. }
  1530. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1531. {
  1532. //int objectsVisitableFromBottom = 0; //for debug
  1533. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1534. ui32 total = 0;
  1535. //calculate actual treasure value range based on remaining value
  1536. ui32 maxVal = desiredValue - currentValue;
  1537. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1538. //roulette wheel
  1539. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1540. {
  1541. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1542. {
  1543. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1544. int3 newVisitablePos = info.nextTreasurePos;
  1545. if (!oi.templ.isVisitableFromTop())
  1546. {
  1547. //objectsVisitableFromBottom++;
  1548. //there must be free tiles under object
  1549. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1550. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1551. continue;
  1552. }
  1553. //NOTE: y coordinate grows downwards
  1554. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1555. {
  1556. bool fitsHere = false;
  1557. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1558. {
  1559. for (auto tile : info.visitableFromTopPositions)
  1560. {
  1561. int3 actualTile = tile + newVisitableOffset;
  1562. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1563. {
  1564. fitsHere = true;
  1565. break;
  1566. }
  1567. }
  1568. for (auto tile : info.visitableFromBottomPositions)
  1569. {
  1570. int3 actualTile = tile + newVisitableOffset;
  1571. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1572. {
  1573. fitsHere = true;
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. else //if new object is not visitable from top, it must be accessible from below or side
  1579. {
  1580. for (auto tile : info.visitableFromTopPositions)
  1581. {
  1582. int3 actualTile = tile + newVisitableOffset;
  1583. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1584. {
  1585. fitsHere = true;
  1586. break;
  1587. }
  1588. }
  1589. for (auto tile : info.visitableFromBottomPositions)
  1590. {
  1591. int3 actualTile = tile + newVisitableOffset;
  1592. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1593. {
  1594. fitsHere = true;
  1595. break;
  1596. }
  1597. }
  1598. }
  1599. if (!fitsHere)
  1600. continue;
  1601. }
  1602. //now check blockmap, including our already reserved pile area
  1603. bool fitsBlockmap = true;
  1604. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1605. blockedOffsets.insert (newVisitableOffset);
  1606. for (auto blockingTile : blockedOffsets)
  1607. {
  1608. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1609. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1610. {
  1611. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1612. break;
  1613. }
  1614. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1615. {
  1616. fitsBlockmap = false;
  1617. break;
  1618. }
  1619. }
  1620. if (!fitsBlockmap)
  1621. continue;
  1622. total += oi.probability;
  1623. //assert (oi.value > 0);
  1624. tresholds.push_back (std::make_pair (total, oi));
  1625. }
  1626. }
  1627. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1628. if (tresholds.empty())
  1629. {
  1630. ObjectInfo oi;
  1631. //Generate pandora Box with gold if the value is extremely high
  1632. if (minValue > 20000) //we don't have object valuable enough
  1633. {
  1634. oi.generateObject = [minValue]() -> CGObjectInstance *
  1635. {
  1636. auto obj = new CGPandoraBox();
  1637. obj->ID = Obj::PANDORAS_BOX;
  1638. obj->subID = 0;
  1639. obj->resources[Res::GOLD] = minValue;
  1640. return obj;
  1641. };
  1642. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1643. oi.value = minValue;
  1644. oi.probability = 0;
  1645. }
  1646. else //generate empty object with 0 value if the value if we can't spawn anything
  1647. {
  1648. oi.generateObject = [gen]() -> CGObjectInstance *
  1649. {
  1650. return nullptr;
  1651. };
  1652. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1653. oi.value = 0; // this field is checked to determine no object
  1654. oi.probability = 0;
  1655. }
  1656. return oi;
  1657. }
  1658. else
  1659. {
  1660. int r = gen->rand.nextInt (1, total);
  1661. for (auto t : tresholds)
  1662. {
  1663. if (r <= t.first)
  1664. return t.second;
  1665. }
  1666. assert (0); //we should never be here
  1667. }
  1668. //FIXME: control reaches end of non-void function. Missing return?
  1669. }
  1670. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1671. {
  1672. ObjectInfo oi;
  1673. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1674. int numZones = gen->getZones().size();
  1675. for (auto primaryID : VLC->objtypeh->knownObjects())
  1676. {
  1677. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1678. {
  1679. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1680. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1681. {
  1682. for (auto temp : handler->getTemplates())
  1683. {
  1684. if (temp.canBePlacedAt(terrainType))
  1685. {
  1686. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1687. {
  1688. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1689. };
  1690. auto rmgInfo = handler->getRMGInfo();
  1691. oi.value = rmgInfo.value;
  1692. oi.probability = rmgInfo.rarity;
  1693. oi.templ = temp;
  1694. oi.maxPerZone = rmgInfo.zoneLimit;
  1695. vstd::amin (oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1696. possibleObjects.push_back (oi);
  1697. }
  1698. }
  1699. }
  1700. }
  1701. }
  1702. //prisons
  1703. //levels 1, 5, 10, 20, 30
  1704. static int prisonExp[] = {0, 5000, 15000, 90000, 500000};
  1705. static int prisonValues[] = {2500, 5000, 10000, 20000, 30000};
  1706. for (int i = 0; i < 5; i++)
  1707. {
  1708. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1709. {
  1710. auto obj = new CGHeroInstance;
  1711. obj->ID = Obj::PRISON;
  1712. std::vector<ui32> possibleHeroes;
  1713. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1714. {
  1715. if (gen->map->allowedHeroes[j])
  1716. possibleHeroes.push_back(j);
  1717. }
  1718. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1719. obj->subID = hid; //will be initialized later
  1720. obj->exp = prisonExp[i];
  1721. obj->setOwner(PlayerColor::NEUTRAL);
  1722. gen->map->allowedHeroes[hid] = false; //ban this hero
  1723. gen->decreasePrisonsRemaining();
  1724. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1725. return obj;
  1726. };
  1727. oi.setTemplate (Obj::PRISON, 0, terrainType);
  1728. oi.value = prisonValues[i];
  1729. oi.probability = 30;
  1730. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1731. possibleObjects.push_back (oi);
  1732. }
  1733. //all following objects are unlimited
  1734. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1735. //dwellings
  1736. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1737. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1738. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1739. for (int i = 0; i < 4; i++)
  1740. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1741. for (auto secondaryID : subObjects)
  1742. {
  1743. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1744. auto creatures = dwellingHandler->getProducedCreatures();
  1745. if (creatures.empty())
  1746. continue;
  1747. auto cre = creatures.front();
  1748. if (cre->faction == townType)
  1749. {
  1750. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1751. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1752. oi.probability = 40;
  1753. for (auto temp : dwellingHandler->getTemplates())
  1754. {
  1755. if (temp.canBePlacedAt(terrainType))
  1756. {
  1757. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1758. {
  1759. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1760. //dwellingHandler->configureObject(obj, gen->rand);
  1761. obj->tempOwner = PlayerColor::NEUTRAL;
  1762. return obj;
  1763. };
  1764. oi.templ = temp;
  1765. possibleObjects.push_back (oi);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1771. for (int i = 0; i < 5; i++)
  1772. {
  1773. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1774. {
  1775. auto obj = new CGArtifact();
  1776. obj->ID = Obj::SPELL_SCROLL;
  1777. obj->subID = 0;
  1778. std::vector<SpellID> out;
  1779. //TODO: unify with cb->getAllowedSpells?
  1780. for (ui32 spellid = 0; spellid < gen->map->allowedSpell.size(); spellid++) //spellh size appears to be greater (?)
  1781. {
  1782. const CSpell *spell = SpellID(spellid).toSpell();
  1783. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1784. {
  1785. out.push_back(spell->id);
  1786. }
  1787. }
  1788. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1789. gen->map->addNewArtifactInstance(a);
  1790. obj->storedArtifact = a;
  1791. return obj;
  1792. };
  1793. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1794. oi.value = scrollValues[i];
  1795. oi.probability = 30;
  1796. possibleObjects.push_back (oi);
  1797. }
  1798. //pandora box with gold
  1799. for (int i = 1; i < 5; i++)
  1800. {
  1801. oi.generateObject = [i]() -> CGObjectInstance *
  1802. {
  1803. auto obj = new CGPandoraBox();
  1804. obj->ID = Obj::PANDORAS_BOX;
  1805. obj->subID = 0;
  1806. obj->resources[Res::GOLD] = i * 5000;
  1807. return obj;
  1808. };
  1809. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1810. oi.value = i * 5000;;
  1811. oi.probability = 5;
  1812. possibleObjects.push_back (oi);
  1813. }
  1814. //pandora box with experience
  1815. for (int i = 1; i < 5; i++)
  1816. {
  1817. oi.generateObject = [i]() -> CGObjectInstance *
  1818. {
  1819. auto obj = new CGPandoraBox();
  1820. obj->ID = Obj::PANDORAS_BOX;
  1821. obj->subID = 0;
  1822. obj->gainedExp = i * 5000;
  1823. return obj;
  1824. };
  1825. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1826. oi.value = i * 6000;;
  1827. oi.probability = 20;
  1828. possibleObjects.push_back (oi);
  1829. }
  1830. //pandora box with creatures
  1831. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1832. for (auto creature : VLC->creh->creatures)
  1833. {
  1834. if (!creature->special && creature->faction == townType)
  1835. {
  1836. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1837. float creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1838. if (creaturesAmount <= 5)
  1839. {
  1840. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1841. if (creaturesAmount < 1)
  1842. continue;
  1843. }
  1844. else if (creaturesAmount <= 12)
  1845. {
  1846. (creaturesAmount /= 2) *= 2;
  1847. }
  1848. else if (creaturesAmount <= 50)
  1849. {
  1850. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1851. }
  1852. else
  1853. {
  1854. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1855. }
  1856. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1857. {
  1858. auto obj = new CGPandoraBox();
  1859. obj->ID = Obj::PANDORAS_BOX;
  1860. obj->subID = 0;
  1861. auto stack = new CStackInstance(creature, creaturesAmount);
  1862. obj->creatures.putStack(SlotID(0), stack);
  1863. return obj;
  1864. };
  1865. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1866. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1867. oi.probability = 3;
  1868. possibleObjects.push_back (oi);
  1869. }
  1870. }
  1871. //Pandora with 12 spells of certain level
  1872. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1873. {
  1874. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1875. {
  1876. auto obj = new CGPandoraBox();
  1877. obj->ID = Obj::PANDORAS_BOX;
  1878. obj->subID = 0;
  1879. std::vector <CSpell *> spells;
  1880. for (auto spell : VLC->spellh->objects)
  1881. {
  1882. if (!spell->isSpecialSpell() && spell->level == i)
  1883. spells.push_back(spell);
  1884. }
  1885. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1886. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1887. {
  1888. obj->spells.push_back (spells[j]->id);
  1889. }
  1890. return obj;
  1891. };
  1892. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1893. oi.value = (i + 1) * 2500; //5000 - 15000
  1894. oi.probability = 2;
  1895. possibleObjects.push_back (oi);
  1896. }
  1897. //Pandora with 15 spells of certain school
  1898. for (int i = 1; i <= 4; i++)
  1899. {
  1900. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1901. {
  1902. auto obj = new CGPandoraBox();
  1903. obj->ID = Obj::PANDORAS_BOX;
  1904. obj->subID = 0;
  1905. std::vector <CSpell *> spells;
  1906. for (auto spell : VLC->spellh->objects)
  1907. {
  1908. if (!spell->isSpecialSpell())
  1909. {
  1910. bool school = false; //TODO: we could have better interface for iterating schools
  1911. switch (i)
  1912. {
  1913. case 1:
  1914. school = spell->air;
  1915. break;
  1916. case 2:
  1917. school = spell->earth;
  1918. break;
  1919. case 3:
  1920. school = spell->fire;
  1921. break;
  1922. case 4:
  1923. school = spell->water;
  1924. break;
  1925. }
  1926. if (school)
  1927. spells.push_back(spell);
  1928. }
  1929. }
  1930. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1931. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1932. {
  1933. obj->spells.push_back (spells[j]->id);
  1934. }
  1935. return obj;
  1936. };
  1937. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1938. oi.value = 15000;
  1939. oi.probability = 2;
  1940. possibleObjects.push_back (oi);
  1941. }
  1942. // Pandora box with 60 random spells
  1943. oi.generateObject = [gen]() -> CGObjectInstance *
  1944. {
  1945. auto obj = new CGPandoraBox();
  1946. obj->ID = Obj::PANDORAS_BOX;
  1947. obj->subID = 0;
  1948. std::vector <CSpell *> spells;
  1949. for (auto spell : VLC->spellh->objects)
  1950. {
  1951. if (!spell->isSpecialSpell())
  1952. spells.push_back(spell);
  1953. }
  1954. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1955. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1956. {
  1957. obj->spells.push_back (spells[j]->id);
  1958. }
  1959. return obj;
  1960. };
  1961. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1962. oi.value = 3000;
  1963. oi.probability = 2;
  1964. possibleObjects.push_back (oi);
  1965. }
  1966. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1967. {
  1968. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1969. }