CRmgTemplateZone.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  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. int CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(int value)
  77. {
  78. nearestObjectDistance = std::max(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. ETerrainType CTileInfo::getTerrainType() const
  105. {
  106. return terrain;
  107. }
  108. void CTileInfo::setTerrainType(ETerrainType value)
  109. {
  110. terrain = value;
  111. }
  112. CRmgTemplateZone::CRmgTemplateZone() :
  113. id(0),
  114. type(ETemplateZoneType::PLAYER_START),
  115. size(1),
  116. townsAreSameType(false),
  117. matchTerrainToTown(true),
  118. townType(0),
  119. terrainType (ETerrainType::GRASS),
  120. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  121. totalDensity(0)
  122. {
  123. townTypes = getDefaultTownTypes();
  124. terrainTypes = getDefaultTerrainTypes();
  125. }
  126. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  127. {
  128. return id;
  129. }
  130. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  131. {
  132. if(value <= 0)
  133. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  134. id = value;
  135. }
  136. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  137. {
  138. return type;
  139. }
  140. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  141. {
  142. type = value;
  143. }
  144. int CRmgTemplateZone::getSize() const
  145. {
  146. return size;
  147. }
  148. void CRmgTemplateZone::setSize(int value)
  149. {
  150. if(value <= 0)
  151. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  152. size = value;
  153. }
  154. boost::optional<int> CRmgTemplateZone::getOwner() const
  155. {
  156. return owner;
  157. }
  158. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  159. {
  160. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  161. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  162. owner = value;
  163. }
  164. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  165. {
  166. return playerTowns;
  167. }
  168. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  169. {
  170. playerTowns = value;
  171. }
  172. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  173. {
  174. return neutralTowns;
  175. }
  176. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  177. {
  178. neutralTowns = value;
  179. }
  180. bool CRmgTemplateZone::getTownsAreSameType() const
  181. {
  182. return townsAreSameType;
  183. }
  184. void CRmgTemplateZone::setTownsAreSameType(bool value)
  185. {
  186. townsAreSameType = value;
  187. }
  188. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  189. {
  190. return townTypes;
  191. }
  192. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  193. {
  194. townTypes = value;
  195. }
  196. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  197. {
  198. std::set<TFaction> defaultTowns;
  199. auto towns = VLC->townh->getDefaultAllowed();
  200. for(int i = 0; i < towns.size(); ++i)
  201. {
  202. if(towns[i]) defaultTowns.insert(i);
  203. }
  204. return defaultTowns;
  205. }
  206. bool CRmgTemplateZone::getMatchTerrainToTown() const
  207. {
  208. return matchTerrainToTown;
  209. }
  210. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  211. {
  212. matchTerrainToTown = value;
  213. }
  214. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  215. {
  216. return terrainTypes;
  217. }
  218. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  219. {
  220. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  221. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  222. terrainTypes = value;
  223. }
  224. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  225. {
  226. std::set<ETerrainType> terTypes;
  227. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  228. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  229. for (auto & allowedTerType : allowedTerTypes)
  230. terTypes.insert(allowedTerType);
  231. return terTypes;
  232. }
  233. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  234. {
  235. mines[res] = amount;
  236. }
  237. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  238. {
  239. return mines;
  240. }
  241. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  242. {
  243. connections.push_back (otherZone);
  244. }
  245. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  246. {
  247. return connections;
  248. }
  249. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  250. {
  251. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  252. zoneMonsterStrength = val;
  253. }
  254. void CRmgTemplateZone::setTotalDensity (ui16 val)
  255. {
  256. totalDensity = val;
  257. }
  258. ui16 CRmgTemplateZone::getTotalDensity () const
  259. {
  260. return totalDensity;
  261. }
  262. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  263. {
  264. treasureInfo.push_back(info);
  265. }
  266. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  267. {
  268. return treasureInfo;
  269. }
  270. std::set<int3>* CRmgTemplateZone::getFreePaths()
  271. {
  272. return &freePaths;
  273. }
  274. float3 CRmgTemplateZone::getCenter() const
  275. {
  276. return center;
  277. }
  278. void CRmgTemplateZone::setCenter(const float3 &f)
  279. {
  280. //limit boundaries to (0,1) square
  281. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  282. }
  283. bool CRmgTemplateZone::pointIsIn(int x, int y)
  284. {
  285. return true;
  286. }
  287. int3 CRmgTemplateZone::getPos() const
  288. {
  289. return pos;
  290. }
  291. void CRmgTemplateZone::setPos(const int3 &Pos)
  292. {
  293. pos = Pos;
  294. }
  295. void CRmgTemplateZone::addTile (const int3 &pos)
  296. {
  297. tileinfo.insert(pos);
  298. }
  299. std::set<int3> CRmgTemplateZone::getTileInfo () const
  300. {
  301. return tileinfo;
  302. }
  303. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  304. {
  305. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  306. //for (auto tile : tileinfo)
  307. //{
  308. // if (tile.dist2d(this->pos) > distance)
  309. // {
  310. // gen->setOccupied(tile, ETileType::USED);
  311. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  312. // }
  313. //}
  314. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  315. {
  316. return tile.dist2d(this->pos) > distance;
  317. });
  318. }
  319. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  320. {
  321. for (auto tile : tileinfo)
  322. {
  323. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  324. {
  325. if (!vstd::contains(this->tileinfo, pos))
  326. {
  327. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  328. {
  329. if (gen->isPossible(pos))
  330. gen->setOccupied (pos, ETileType::BLOCKED);
  331. });
  332. }
  333. });
  334. }
  335. }
  336. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  337. {
  338. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  339. std::set<int3> possibleTiles;
  340. std::set<int3> tilesToClear; //will be set clear
  341. std::set<int3> tilesToIgnore; //will be erased in this iteration
  342. //the more treasure density, the greater distance between paths. Scaling is experimental.
  343. const float minDistance = std::sqrt(totalDensity * 3);
  344. for (auto tile : tileinfo)
  345. {
  346. if (gen->isFree(tile))
  347. clearedTiles.push_back(tile);
  348. else if (gen->isPossible(tile))
  349. possibleTiles.insert(tile);
  350. }
  351. if (clearedTiles.empty()) //this should come from zone connections
  352. {
  353. clearedTiles.push_back(pos); //zone center should be always clear
  354. }
  355. while (possibleTiles.size())
  356. {
  357. for (auto tileToMakePath : possibleTiles)
  358. {
  359. //find closest free tile
  360. float currentDistance = 1e10;
  361. int3 closestTile (-1,-1,-1);
  362. for (auto clearTile : clearedTiles)
  363. {
  364. float distance = tileToMakePath.dist2d(clearTile);
  365. if (distance < currentDistance)
  366. {
  367. currentDistance = distance;
  368. closestTile = clearTile;
  369. }
  370. if (currentDistance <= minDistance)
  371. {
  372. //this tile is close enough. Forget about it and check next one
  373. tilesToIgnore.insert (tileToMakePath);
  374. break;
  375. }
  376. }
  377. //if tiles is not close enough, make path to it
  378. if (currentDistance > minDistance)
  379. {
  380. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  381. break; //next iteration - use already cleared tiles
  382. }
  383. }
  384. for (auto tileToClear : tilesToClear)
  385. {
  386. //move cleared tiles from one set to another
  387. clearedTiles.push_back(tileToClear);
  388. vstd::erase_if_present(possibleTiles, tileToClear);
  389. }
  390. for (auto tileToClear : tilesToIgnore)
  391. {
  392. //these tiles are already connected, ignore them
  393. vstd::erase_if_present(possibleTiles, tileToClear);
  394. }
  395. if (tilesToClear.empty()) //nothing else can be done (?)
  396. break;
  397. tilesToClear.clear(); //empty this container
  398. tilesToIgnore.clear();
  399. }
  400. for (auto tile : clearedTiles)
  401. {
  402. freePaths.insert(tile);
  403. }
  404. if (0) //enable to debug
  405. {
  406. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  407. int levels = gen->map->twoLevel ? 2 : 1;
  408. int width = gen->map->width;
  409. int height = gen->map->height;
  410. for (int k = 0; k < levels; k++)
  411. {
  412. for(int j=0; j<height; j++)
  413. {
  414. for (int i=0; i<width; i++)
  415. {
  416. out << (int)vstd::contains(freePaths, int3(i,j,k));
  417. }
  418. out << std::endl;
  419. }
  420. out << std::endl;
  421. }
  422. }
  423. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  424. }
  425. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  426. {
  427. /*
  428. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  429. do not leave zone border
  430. */
  431. bool result = false;
  432. bool end = false;
  433. int3 currentPos = src;
  434. float distance = currentPos.dist2dSQ (dst);
  435. while (!end)
  436. {
  437. if (currentPos == dst)
  438. {
  439. result = true;
  440. break;
  441. }
  442. auto lastDistance = distance;
  443. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  444. {
  445. if (!result) //not sure if lambda is worth it...
  446. {
  447. if (pos == dst)
  448. {
  449. result = true;
  450. end = true;
  451. }
  452. if (pos.dist2dSQ (dst) < distance)
  453. {
  454. if (!gen->isBlocked(pos))
  455. {
  456. if (vstd::contains (tileinfo, pos))
  457. {
  458. if (gen->isPossible(pos))
  459. {
  460. gen->setOccupied (pos, ETileType::FREE);
  461. if (clearedTiles)
  462. clearedTiles->insert(pos);
  463. currentPos = pos;
  464. distance = currentPos.dist2dSQ (dst);
  465. }
  466. else if (gen->isFree(pos))
  467. {
  468. end = true;
  469. result = true;
  470. }
  471. else
  472. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  473. }
  474. }
  475. }
  476. }
  477. });
  478. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  479. {
  480. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  481. break;
  482. }
  483. }
  484. return result;
  485. }
  486. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  487. {
  488. requiredObjects.push_back(std::make_pair(obj, strength));
  489. }
  490. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  491. {
  492. //precalculate actual (randomized) monster strength based on this post
  493. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  494. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  495. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  496. static const int value1[] = {2500, 1500, 1000, 500, 0};
  497. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  498. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  499. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  500. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  501. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  502. strength = strength1 + strength2;
  503. if (strength < 2000)
  504. return false; //no guard at all
  505. CreatureID creId = CreatureID::NONE;
  506. int amount = 0;
  507. std::vector<CreatureID> possibleCreatures;
  508. for (auto cre : VLC->creh->creatures)
  509. {
  510. if (cre->special)
  511. continue;
  512. 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
  513. {
  514. possibleCreatures.push_back(cre->idNumber);
  515. }
  516. }
  517. if (possibleCreatures.size())
  518. {
  519. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  520. amount = strength / VLC->creh->creatures[creId]->AIValue;
  521. if (amount >= 4)
  522. amount *= gen->rand.nextDouble(0.75, 1.25);
  523. }
  524. else //just pick any available creature
  525. {
  526. creId = CreatureID(132); //Azure Dragon
  527. amount = strength / VLC->creh->creatures[creId]->AIValue;
  528. }
  529. auto guard = new CGCreature();
  530. guard->ID = Obj::MONSTER;
  531. guard->subID = creId;
  532. auto hlp = new CStackInstance(creId, amount);
  533. //will be set during initialization
  534. guard->putStack(SlotID(0), hlp);
  535. placeObject(gen, guard, pos);
  536. return true;
  537. }
  538. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  539. {
  540. CTreasurePileInfo info;
  541. std::map<int3, CGObjectInstance *> treasures;
  542. std::set<int3> boundary;
  543. int3 guardPos (-1,-1,-1);
  544. info.nextTreasurePos = pos;
  545. //default values
  546. int maxValue = 5000;
  547. int minValue = 1500;
  548. if (treasureInfo.size())
  549. {
  550. //roulette wheel
  551. int r = gen->rand.nextInt (1, totalDensity);
  552. for (auto t : treasureInfo)
  553. {
  554. if (r <= t.threshold)
  555. {
  556. maxValue = t.max;
  557. minValue = t.min;
  558. break;
  559. }
  560. }
  561. }
  562. int currentValue = 0;
  563. CGObjectInstance * object = nullptr;
  564. while (currentValue < minValue)
  565. {
  566. treasures[info.nextTreasurePos] = nullptr;
  567. for (auto treasurePos : treasures)
  568. {
  569. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  570. {
  571. boundary.insert(pos);
  572. });
  573. }
  574. for (auto treasurePos : treasures)
  575. {
  576. //leaving only boundary around objects
  577. vstd::erase_if_present (boundary, treasurePos.first);
  578. }
  579. for (auto tile : boundary)
  580. {
  581. //we can't extend boundary anymore
  582. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  583. break;
  584. }
  585. int remaining = maxValue - currentValue;
  586. ObjectInfo oi = getRandomObject(gen, info, remaining);
  587. object = oi.generateObject();
  588. if (!object)
  589. {
  590. vstd::erase_if_present(treasures, info.nextTreasurePos);
  591. break;
  592. }
  593. else
  594. {
  595. //update treasure pile area
  596. int3 visitablePos = oi.templ.getVisitableOffset() + info.nextTreasurePos;
  597. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  598. if (oi.templ.isVisitableFromTop())
  599. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  600. else
  601. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  602. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  603. {
  604. info.occupiedPositions.insert(info.nextTreasurePos + blockedOffset);
  605. info.blockedPositions.insert(info.nextTreasurePos + blockedOffset);
  606. }
  607. info.occupiedPositions.insert(visitablePos);
  608. }
  609. currentValue += oi.value;
  610. treasures[info.nextTreasurePos] = object;
  611. //now find place for next object
  612. int3 placeFound(-1,-1,-1);
  613. for (auto tile : boundary)
  614. {
  615. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  616. {
  617. bool here = true;
  618. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  619. {
  620. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  621. here = false;
  622. });
  623. if (here)
  624. {
  625. placeFound = tile;
  626. break;
  627. }
  628. }
  629. }
  630. if (placeFound.valid())
  631. info.nextTreasurePos = placeFound;
  632. }
  633. if (treasures.size())
  634. {
  635. //find object closest to zone center, then connect it to the middle of the zone
  636. int3 closestFreeTile (-1,-1,-1);
  637. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  638. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  639. else
  640. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  641. int3 closestTile = int3(-1,-1,-1);
  642. float minDistance = 1e10;
  643. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  644. {
  645. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  646. {
  647. closestTile = visitablePos - int3 (0,-1, 0); //start below object, possibly even outside the map (?)
  648. minDistance = closestFreeTile.dist2d(visitablePos);
  649. }
  650. }
  651. if (!closestTile.valid())
  652. {
  653. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  654. {
  655. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  656. {
  657. closestTile = visitablePos;
  658. minDistance = closestFreeTile.dist2d(visitablePos);
  659. }
  660. }
  661. }
  662. assert (closestTile.valid());
  663. for (auto tile : info.occupiedPositions)
  664. {
  665. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  666. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  667. }
  668. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  669. {
  670. //we can't connect this pile, just block it off and start over
  671. for (auto treasure : treasures)
  672. {
  673. if (gen->isPossible(treasure.first))
  674. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  675. }
  676. return true;
  677. }
  678. for (auto tile : boundary) //guard must be standing there
  679. {
  680. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  681. {
  682. guardPos = tile;
  683. break;
  684. }
  685. }
  686. if (guardPos.valid())
  687. {
  688. for (auto treasure : treasures)
  689. {
  690. int3 visitableOffset = treasure.second->getVisitableOffset();
  691. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  692. }
  693. if (addMonster(gen, guardPos, currentValue))
  694. {//block only if the object is guarded
  695. for (auto tile : boundary)
  696. {
  697. if (gen->isPossible(tile))
  698. gen->setOccupied (tile, ETileType::BLOCKED);
  699. }
  700. }
  701. }
  702. else //we couldn't make a connection to this location, block it
  703. {
  704. for (auto treasure : treasures)
  705. {
  706. if (gen->isPossible(treasure.first))
  707. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  708. }
  709. }
  710. return true;
  711. }
  712. else //we did not place eveyrthing successfully
  713. return false;
  714. }
  715. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  716. {
  717. //FIXME: handle case that this player is not present -> towns should be set to neutral
  718. int totalTowns = 0;
  719. auto addNewTowns = [&totalTowns, gen, this](int count, bool hasFort, PlayerColor player)
  720. {
  721. for (int i = 0; i < count; i++)
  722. {
  723. auto town = new CGTownInstance();
  724. town->ID = Obj::TOWN;
  725. if (this->townsAreSameType)
  726. town->subID = townType;
  727. else
  728. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  729. town->tempOwner = player;
  730. if (hasFort)
  731. town->builtBuildings.insert(BuildingID::FORT);
  732. town->builtBuildings.insert(BuildingID::DEFAULT);
  733. if (!totalTowns)
  734. {
  735. //first town in zone sets the facton of entire zone
  736. town->subID = townType;
  737. //register MAIN town of zone
  738. gen->registerZone(town->subID);
  739. //first town in zone goes in the middle
  740. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  741. }
  742. else
  743. addRequiredObject (town);
  744. totalTowns++;
  745. }
  746. };
  747. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  748. {
  749. //set zone types to player faction, generate main town
  750. logGlobal->infoStream() << "Preparing playing zone";
  751. int player_id = *owner - 1;
  752. auto & playerInfo = gen->map->players[player_id];
  753. if (playerInfo.canAnyonePlay())
  754. {
  755. PlayerColor player(player_id);
  756. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  757. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  758. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  759. auto town = new CGTownInstance();
  760. town->ID = Obj::TOWN;
  761. town->subID = townType;
  762. town->tempOwner = player;
  763. town->builtBuildings.insert(BuildingID::FORT);
  764. town->builtBuildings.insert(BuildingID::DEFAULT);
  765. //towns are big objects and should be centered around visitable position
  766. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  767. totalTowns++;
  768. //register MAIN town of zone only
  769. gen->registerZone (town->subID);
  770. logGlobal->traceStream() << "Fill player info " << player_id;
  771. // Update player info
  772. playerInfo.allowedFactions.clear();
  773. playerInfo.allowedFactions.insert (townType);
  774. playerInfo.hasMainTown = true;
  775. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  776. playerInfo.generateHeroAtMainTown = true;
  777. //now create actual towns
  778. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  779. addNewTowns (playerTowns.getTownCount(), false, player);
  780. //requiredObjects.push_back(town);
  781. }
  782. else
  783. {
  784. type = ETemplateZoneType::TREASURE;
  785. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  786. logGlobal->infoStream() << "Skipping this zone cause no player";
  787. }
  788. }
  789. else //no player
  790. {
  791. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  792. }
  793. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  794. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  795. }
  796. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  797. {
  798. if (matchTerrainToTown)
  799. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  800. else
  801. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  802. //TODO: allow new types of terrain?
  803. if (pos.z)
  804. {
  805. if (terrainType != ETerrainType::LAVA)
  806. terrainType = ETerrainType::SUBTERRANEAN;
  807. }
  808. else
  809. {
  810. if (terrainType == ETerrainType::SUBTERRANEAN)
  811. terrainType = ETerrainType::DIRT;
  812. }
  813. paintZoneTerrain (gen, terrainType);
  814. }
  815. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  816. {
  817. std::vector<int3> tiles;
  818. for (auto tile : tileinfo)
  819. {
  820. tiles.push_back (tile);
  821. }
  822. gen->editManager->getTerrainSelection().setSelection(tiles);
  823. gen->editManager->drawTerrain(terrainType, &gen->rand);
  824. }
  825. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  826. {
  827. std::vector<Res::ERes> required_mines;
  828. required_mines.push_back(Res::ERes::WOOD);
  829. required_mines.push_back(Res::ERes::ORE);
  830. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  831. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  832. //TODO: factory / copy constructor?
  833. for (const auto & res : woodOre)
  834. {
  835. //TODO: these 2 should be close to town (within 12 tiles radius)
  836. for (int i = 0; i < mines[res]; i++)
  837. {
  838. auto mine = new CGMine();
  839. mine->ID = Obj::MINE;
  840. mine->subID = static_cast<si32>(res);
  841. mine->producedResource = res;
  842. mine->producedQuantity = mine->defaultResProduction();
  843. addRequiredObject(mine, 1500);
  844. }
  845. }
  846. for (const auto & res : preciousResources)
  847. {
  848. for (int i = 0; i < mines[res]; i++)
  849. {
  850. auto mine = new CGMine();
  851. mine->ID = Obj::MINE;
  852. mine->subID = static_cast<si32>(res);
  853. mine->producedResource = res;
  854. mine->producedQuantity = mine->defaultResProduction();
  855. addRequiredObject(mine, 3500);
  856. }
  857. }
  858. for (int i = 0; i < mines[Res::GOLD]; i++)
  859. {
  860. auto mine = new CGMine();
  861. mine->ID = Obj::MINE;
  862. mine->subID = static_cast<si32>(Res::GOLD);
  863. mine->producedResource = Res::GOLD;
  864. mine->producedQuantity = mine->defaultResProduction();
  865. addRequiredObject(mine, 7000);
  866. }
  867. return true;
  868. }
  869. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  870. {
  871. logGlobal->infoStream() << "Creating required objects";
  872. for(const auto &obj : requiredObjects)
  873. {
  874. int3 pos;
  875. logGlobal->traceStream() << "Looking for place";
  876. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  877. {
  878. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  879. //TODO CLEANUP!
  880. return false;
  881. }
  882. logGlobal->traceStream() << "Place found";
  883. placeObject(gen, obj.first, pos);
  884. guardObject (gen, obj.first, obj.second);
  885. }
  886. return true;
  887. }
  888. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  889. {
  890. const double minDistance = 3;
  891. do {
  892. int3 pos;
  893. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  894. {
  895. break;
  896. }
  897. createTreasurePile (gen, pos);
  898. } while(true);
  899. }
  900. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  901. {
  902. if (pos.z) //underground
  903. {
  904. std::vector<int3> rockTiles;
  905. for (auto tile : tileinfo)
  906. {
  907. if (gen->shouldBeBlocked(tile))
  908. {
  909. bool placeRock = true;
  910. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  911. {
  912. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  913. placeRock = false;
  914. });
  915. if (placeRock)
  916. {
  917. rockTiles.push_back(tile);
  918. }
  919. }
  920. }
  921. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  922. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  923. //for (auto tile : rockTiles)
  924. //{
  925. // gen->setOccupied (tile, ETileType::USED);
  926. // gen->foreach_neighbour (tile, [gen](int3 &pos)
  927. // {
  928. // if (!gen->isUsed(pos))
  929. // gen->setOccupied (pos, ETileType::BLOCKED);
  930. // });
  931. //}
  932. }
  933. //get all possible obstacles for this terrain
  934. for (auto primaryID : VLC->objtypeh->knownObjects())
  935. {
  936. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  937. {
  938. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  939. if (handler->isStaticObject())
  940. {
  941. for (auto temp : handler->getTemplates())
  942. {
  943. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  944. possibleObstacles.push_back(temp);
  945. }
  946. }
  947. }
  948. }
  949. auto sel = gen->editManager->getTerrainSelection();
  950. sel.clearSelection();
  951. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  952. {
  953. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  954. int3 obstaclePos = tile - temp.getBlockMapOffset();
  955. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  956. {
  957. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  958. placeObject(gen, obj, obstaclePos);
  959. return true;
  960. }
  961. return false;
  962. };
  963. for (auto tile : tileinfo)
  964. {
  965. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  966. {
  967. while (!tryToPlaceObstacleHere(tile));
  968. }
  969. else if (gen->isPossible(tile))
  970. {
  971. //try to place random obstacle once - if not possible, leave it clear
  972. tryToPlaceObstacleHere(tile);
  973. }
  974. }
  975. }
  976. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  977. {
  978. initTownType(gen);
  979. initTerrainType(gen);
  980. addAllPossibleObjects (gen);
  981. placeMines(gen);
  982. createRequiredObjects(gen);
  983. fractalize(gen); //after required objects are created and linked with their own paths
  984. createTreasures(gen);
  985. createObstacles(gen);
  986. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  987. return true;
  988. }
  989. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  990. {
  991. //si32 min_dist = sqrt(tileinfo.size()/density);
  992. int best_distance = 0;
  993. bool result = false;
  994. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  995. for(auto tile : tileinfo)
  996. {
  997. auto dist = gen->getTile(tile).getNearestObjectDistance();
  998. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  999. {
  1000. bool allTilesAvailable = true;
  1001. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  1002. {
  1003. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  1004. {
  1005. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1006. }
  1007. });
  1008. if (allTilesAvailable)
  1009. {
  1010. best_distance = dist;
  1011. pos = tile;
  1012. result = true;
  1013. }
  1014. }
  1015. }
  1016. if (result)
  1017. {
  1018. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1019. }
  1020. return result;
  1021. }
  1022. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1023. {
  1024. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1025. return false;
  1026. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1027. for (auto blockingTile : tilesBlockedByObject)
  1028. {
  1029. int3 t = pos + blockingTile;
  1030. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1031. {
  1032. return false; //if at least one tile is not possible, object can't be placed here
  1033. }
  1034. }
  1035. return true;
  1036. }
  1037. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, std::set<int3> &tilesBlockedByObject) const
  1038. {
  1039. bool accessible = false;
  1040. for (int x = -1; x < 2; x++)
  1041. {
  1042. for (int y = -1; y <2; y++)
  1043. {
  1044. if (x && y) //check only if object is visitable from another tile
  1045. {
  1046. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1047. if (!vstd::contains(tilesBlockedByObject, offset))
  1048. {
  1049. int3 nearbyPos = tile + offset;
  1050. if (gen->map->isInTheMap(nearbyPos))
  1051. {
  1052. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1053. accessible = true;
  1054. }
  1055. }
  1056. }
  1057. };
  1058. }
  1059. return accessible;
  1060. }
  1061. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1062. {
  1063. //we need object apperance to deduce free tiles
  1064. if (obj->appearance.id == Obj::NO_OBJ)
  1065. {
  1066. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1067. if (templates.empty())
  1068. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1069. obj->appearance = templates.front();
  1070. }
  1071. //si32 min_dist = sqrt(tileinfo.size()/density);
  1072. int best_distance = 0;
  1073. bool result = false;
  1074. //si32 w = gen->map->width;
  1075. //si32 h = gen->map->height;
  1076. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1077. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1078. for (auto tile : tileinfo)
  1079. {
  1080. //object must be accessible from at least one surounding tile
  1081. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1082. continue;
  1083. auto ti = gen->getTile(tile);
  1084. auto dist = ti.getNearestObjectDistance();
  1085. //avoid borders
  1086. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1087. {
  1088. bool allTilesAvailable = true;
  1089. for (auto blockingTile : tilesBlockedByObject)
  1090. {
  1091. int3 t = tile + blockingTile;
  1092. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1093. {
  1094. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1095. break;
  1096. }
  1097. }
  1098. if (allTilesAvailable)
  1099. {
  1100. best_distance = dist;
  1101. pos = tile;
  1102. result = true;
  1103. }
  1104. }
  1105. }
  1106. if (result)
  1107. {
  1108. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1109. }
  1110. return result;
  1111. }
  1112. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1113. {
  1114. if (!gen->map->isInTheMap(pos))
  1115. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1116. object->pos = pos;
  1117. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1118. 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()));
  1119. for (auto tile : object->getBlockedPos())
  1120. {
  1121. if (!gen->map->isInTheMap(tile))
  1122. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1123. }
  1124. if (object->appearance.id == Obj::NO_OBJ)
  1125. {
  1126. auto terrainType = gen->map->getTile(pos).terType;
  1127. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1128. if (templates.empty())
  1129. 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));
  1130. object->appearance = templates.front();
  1131. }
  1132. gen->map->addBlockVisTiles(object);
  1133. gen->editManager->insertObject(object, pos);
  1134. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1135. }
  1136. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1137. {
  1138. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1139. checkAndPlaceObject (gen, object, pos);
  1140. auto points = object->getBlockedPos();
  1141. if (object->isVisitable())
  1142. points.insert(pos + object->getVisitableOffset());
  1143. points.insert(pos);
  1144. for(auto p : points)
  1145. {
  1146. if (gen->map->isInTheMap(p))
  1147. {
  1148. gen->setOccupied(p, ETileType::USED);
  1149. }
  1150. }
  1151. for(auto tile : tileinfo)
  1152. {
  1153. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1154. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1155. }
  1156. }
  1157. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str)
  1158. {
  1159. placeObject(gen, object, pos);
  1160. guardObject(gen, object, str);
  1161. }
  1162. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1163. {
  1164. //get all tiles from which this object can be accessed
  1165. int3 visitable = object->visitablePos();
  1166. std::vector<int3> tiles;
  1167. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1168. gen->foreach_neighbour(visitable, [&](int3& pos)
  1169. {
  1170. if (gen->isPossible(pos))
  1171. {
  1172. if (!vstd::contains(tilesBlockedByObject, pos))
  1173. {
  1174. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1175. {
  1176. tiles.push_back(pos);
  1177. }
  1178. }
  1179. };
  1180. });
  1181. return tiles;
  1182. }
  1183. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  1184. {
  1185. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1186. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1187. int3 guardTile(-1,-1,-1);
  1188. for (auto tile : tiles)
  1189. {
  1190. //crunching path may fail if center of teh zone is dirrectly over wide object
  1191. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id)) //make sure object is accessible before surrounding it with blocked tiles
  1192. {
  1193. guardTile = tile;
  1194. break;
  1195. }
  1196. }
  1197. if (!guardTile.valid())
  1198. {
  1199. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1200. return false;
  1201. }
  1202. if (addMonster (gen, guardTile, str)) //do not place obstacles around unguarded object
  1203. {
  1204. for (auto pos : tiles)
  1205. {
  1206. if (!gen->isFree(pos))
  1207. gen->setOccupied(pos, ETileType::BLOCKED);
  1208. }
  1209. gen->setOccupied (guardTile, ETileType::USED);
  1210. }
  1211. else //allow no guard or other object in front of this object
  1212. {
  1213. for (auto tile : tiles)
  1214. gen->setOccupied (tile, ETileType::FREE);
  1215. }
  1216. return true;
  1217. }
  1218. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, CTreasurePileInfo &info, ui32 value)
  1219. {
  1220. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1221. ui32 total = 0;
  1222. ui32 minValue = 0.25f * value;
  1223. //roulette wheel
  1224. for (auto oi : possibleObjects)
  1225. {
  1226. if (oi.value >= minValue && oi.value <= value)
  1227. {
  1228. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1229. int3 newVisitablePos = info.nextTreasurePos;
  1230. if (!oi.templ.isVisitableFromTop())
  1231. {
  1232. //there must be free tiles under object
  1233. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, oi.templ.getBlockedOffsets()))
  1234. continue;
  1235. }
  1236. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1237. {
  1238. bool fitsHere = false;
  1239. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1240. {
  1241. for (auto tile : info.visitableFromTopPositions)
  1242. {
  1243. int3 actualTile = tile + newVisitableOffset;
  1244. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1245. {
  1246. fitsHere = true;
  1247. break;
  1248. }
  1249. }
  1250. for (auto tile : info.visitableFromBottomPositions)
  1251. {
  1252. int3 actualTile = tile + newVisitableOffset;
  1253. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing static object from side or bottom only
  1254. {
  1255. fitsHere = true;
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. else //if new object is not visitable from top, it must be accessible from below or side
  1261. {
  1262. for (auto tile : info.visitableFromTopPositions)
  1263. {
  1264. int3 actualTile = tile + newVisitableOffset;
  1265. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing removable object from top or side only
  1266. {
  1267. fitsHere = true;
  1268. break;
  1269. }
  1270. }
  1271. for (auto tile : info.visitableFromBottomPositions)
  1272. {
  1273. int3 actualTile = tile + newVisitableOffset;
  1274. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1275. {
  1276. fitsHere = true;
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. if (!fitsHere)
  1282. continue;
  1283. }
  1284. //now check blockmap, including our already reserved pile area
  1285. bool fitsBlockmap = true;
  1286. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1287. blockedOffsets.insert (newVisitableOffset);
  1288. for (auto blockingTile : blockedOffsets)
  1289. {
  1290. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1291. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1292. {
  1293. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1294. break;
  1295. }
  1296. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1297. {
  1298. fitsBlockmap = false;
  1299. break;
  1300. }
  1301. }
  1302. if (!fitsBlockmap)
  1303. continue;
  1304. total += oi.probability;
  1305. tresholds.push_back (std::make_pair (total, oi));
  1306. }
  1307. }
  1308. //Generate pandora Box with gold if the value is extremely high
  1309. ObjectInfo oi;
  1310. if (tresholds.empty())
  1311. {
  1312. if (minValue > 20000) //we don't have object valuable enough
  1313. {
  1314. oi.generateObject = [minValue]() -> CGObjectInstance *
  1315. {
  1316. auto obj = new CGPandoraBox();
  1317. obj->ID = Obj::PANDORAS_BOX;
  1318. obj->subID = 0;
  1319. obj->resources[Res::GOLD] = minValue;
  1320. return obj;
  1321. };
  1322. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1323. oi.value = minValue;
  1324. oi.probability = 0;
  1325. }
  1326. else
  1327. {
  1328. oi.generateObject = [gen]() -> CGObjectInstance *
  1329. {
  1330. return nullptr;
  1331. };
  1332. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1333. oi.value = 0;
  1334. oi.probability = 0;
  1335. }
  1336. return oi;
  1337. }
  1338. int r = gen->rand.nextInt (1, total);
  1339. for (auto t : tresholds)
  1340. {
  1341. if (r <= t.first)
  1342. return t.second;
  1343. }
  1344. //FIXME: control reaches end of non-void function. Missing return?
  1345. }
  1346. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1347. {
  1348. ObjectInfo oi;
  1349. for (auto primaryID : VLC->objtypeh->knownObjects())
  1350. {
  1351. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1352. {
  1353. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1354. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1355. {
  1356. for (auto temp : handler->getTemplates())
  1357. {
  1358. if (temp.canBePlacedAt(terrainType))
  1359. {
  1360. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1361. {
  1362. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1363. };
  1364. oi.value = handler->getRMGInfo().value;
  1365. oi.probability = handler->getRMGInfo().rarity;
  1366. oi.templ = temp;
  1367. possibleObjects.push_back (oi);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. }
  1373. //dwellings
  1374. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1375. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1376. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1377. for (int i = 0; i < 4; i++)
  1378. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1379. for (auto secondaryID : subObjects)
  1380. {
  1381. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1382. auto creatures = dwellingHandler->getProducedCreatures();
  1383. if (creatures.empty())
  1384. continue;
  1385. auto cre = creatures.front();
  1386. if (cre->faction == townType)
  1387. {
  1388. oi.value = cre->AIValue * cre->growth * (1 + (float)(gen->getZoneCount(cre->faction)) / gen->getTotalZoneCount() + (float)(gen->getZoneCount(cre->faction) / 2)); //TODO: include town count in formula
  1389. oi.probability = 40;
  1390. for (auto temp : dwellingHandler->getTemplates())
  1391. {
  1392. if (temp.canBePlacedAt(terrainType))
  1393. {
  1394. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1395. {
  1396. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1397. //dwellingHandler->configureObject(obj, gen->rand);
  1398. obj->tempOwner = PlayerColor::NEUTRAL;
  1399. return obj;
  1400. };
  1401. oi.templ = temp;
  1402. possibleObjects.push_back (oi);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1408. for (int i = 0; i < 5; i++)
  1409. {
  1410. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1411. {
  1412. auto obj = new CGArtifact();
  1413. obj->ID = Obj::SPELL_SCROLL;
  1414. obj->subID = 0;
  1415. std::vector<SpellID> out;
  1416. //TODO: unify with cb->getAllowedSpells?
  1417. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1418. {
  1419. const CSpell *spell = SpellID(i).toSpell();
  1420. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1421. {
  1422. out.push_back(spell->id);
  1423. }
  1424. }
  1425. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1426. gen->map->addNewArtifactInstance(a);
  1427. obj->storedArtifact = a;
  1428. return obj;
  1429. };
  1430. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1431. oi.value = scrollValues[i];
  1432. oi.probability = 30;
  1433. possibleObjects.push_back (oi);
  1434. }
  1435. //pandora box with gold
  1436. for (int i = 1; i < 5; i++)
  1437. {
  1438. oi.generateObject = [i]() -> CGObjectInstance *
  1439. {
  1440. auto obj = new CGPandoraBox();
  1441. obj->ID = Obj::PANDORAS_BOX;
  1442. obj->subID = 0;
  1443. obj->resources[Res::GOLD] = i * 5000;
  1444. return obj;
  1445. };
  1446. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1447. oi.value = i * 5000;;
  1448. oi.probability = 5;
  1449. possibleObjects.push_back (oi);
  1450. }
  1451. //pandora box with experience
  1452. for (int i = 1; i < 5; i++)
  1453. {
  1454. oi.generateObject = [i]() -> CGObjectInstance *
  1455. {
  1456. auto obj = new CGPandoraBox();
  1457. obj->ID = Obj::PANDORAS_BOX;
  1458. obj->subID = 0;
  1459. obj->gainedExp = i * 5000;
  1460. return obj;
  1461. };
  1462. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1463. oi.value = i * 6000;;
  1464. oi.probability = 20;
  1465. possibleObjects.push_back (oi);
  1466. }
  1467. //pandora box with creatures
  1468. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1469. for (auto creature : VLC->creh->creatures)
  1470. {
  1471. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1472. {
  1473. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1474. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1475. if (creaturesAmount <= 5)
  1476. {
  1477. }
  1478. else if (creaturesAmount <= 12)
  1479. {
  1480. (creaturesAmount /= 2) *= 2;
  1481. }
  1482. else if (creaturesAmount <= 50)
  1483. {
  1484. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1485. }
  1486. else if (creaturesAmount <= 12)
  1487. {
  1488. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1489. }
  1490. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1491. {
  1492. auto obj = new CGPandoraBox();
  1493. obj->ID = Obj::PANDORAS_BOX;
  1494. obj->subID = 0;
  1495. auto stack = new CStackInstance(creature, creaturesAmount);
  1496. obj->creatures.putStack(SlotID(0), stack);
  1497. return obj;
  1498. };
  1499. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1500. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1501. oi.probability = 3;
  1502. possibleObjects.push_back (oi);
  1503. }
  1504. }
  1505. //Pandora with 12 spells of certain level
  1506. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1507. {
  1508. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1509. {
  1510. auto obj = new CGPandoraBox();
  1511. obj->ID = Obj::PANDORAS_BOX;
  1512. obj->subID = 0;
  1513. std::vector <CSpell *> spells;
  1514. for (auto spell : VLC->spellh->objects)
  1515. {
  1516. if (!spell->isSpecialSpell() && spell->level == i)
  1517. spells.push_back(spell);
  1518. }
  1519. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1520. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1521. {
  1522. obj->spells.push_back (spells[j]->id);
  1523. }
  1524. return obj;
  1525. };
  1526. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1527. oi.value = (i + 1) * 2500; //5000 - 15000
  1528. oi.probability = 2;
  1529. possibleObjects.push_back (oi);
  1530. }
  1531. //Pandora with 15 spells of certain school
  1532. for (int i = 1; i <= 4; i++)
  1533. {
  1534. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1535. {
  1536. auto obj = new CGPandoraBox();
  1537. obj->ID = Obj::PANDORAS_BOX;
  1538. obj->subID = 0;
  1539. std::vector <CSpell *> spells;
  1540. for (auto spell : VLC->spellh->objects)
  1541. {
  1542. if (!spell->isSpecialSpell())
  1543. {
  1544. bool school = false; //TODO: we could have better interface for iterating schools
  1545. switch (i)
  1546. {
  1547. case 1:
  1548. school = spell->air;
  1549. case 2:
  1550. school = spell->earth;
  1551. case 3:
  1552. school = spell->fire;
  1553. case 4:
  1554. school = spell->water;
  1555. }
  1556. if (school)
  1557. spells.push_back(spell);
  1558. }
  1559. }
  1560. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1561. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1562. {
  1563. obj->spells.push_back (spells[j]->id);
  1564. }
  1565. return obj;
  1566. };
  1567. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1568. oi.value = 15000;
  1569. oi.probability = 2;
  1570. possibleObjects.push_back (oi);
  1571. }
  1572. // Pandora box with 60 random spells
  1573. oi.generateObject = [gen]() -> CGObjectInstance *
  1574. {
  1575. auto obj = new CGPandoraBox();
  1576. obj->ID = Obj::PANDORAS_BOX;
  1577. obj->subID = 0;
  1578. std::vector <CSpell *> spells;
  1579. for (auto spell : VLC->spellh->objects)
  1580. {
  1581. if (!spell->isSpecialSpell())
  1582. spells.push_back(spell);
  1583. }
  1584. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1585. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1586. {
  1587. obj->spells.push_back (spells[j]->id);
  1588. }
  1589. return obj;
  1590. };
  1591. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1592. oi.value = 3000;
  1593. oi.probability = 2;
  1594. possibleObjects.push_back (oi);
  1595. }
  1596. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1597. {
  1598. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1599. }