CRmgTemplateZone.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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/CObjectClassesHandler.h"
  19. #include "../mapObjects/CGPandoraBox.h"
  20. #include "../mapObjects/CRewardableObject.h"
  21. class CMap;
  22. class CMapEditManager;
  23. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  24. {
  25. }
  26. int CRmgTemplateZone::CTownInfo::getTownCount() const
  27. {
  28. return townCount;
  29. }
  30. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  31. {
  32. if(value < 0)
  33. throw rmgException("Negative value for town count not allowed.");
  34. townCount = value;
  35. }
  36. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  37. {
  38. return castleCount;
  39. }
  40. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  41. {
  42. if(value < 0)
  43. throw rmgException("Negative value for castle count not allowed.");
  44. castleCount = value;
  45. }
  46. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  47. {
  48. return townDensity;
  49. }
  50. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  51. {
  52. if(value < 0)
  53. throw rmgException("Negative value for town density not allowed.");
  54. townDensity = value;
  55. }
  56. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  57. {
  58. return castleDensity;
  59. }
  60. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  61. {
  62. if(value < 0)
  63. throw rmgException("Negative value for castle density not allowed.");
  64. castleDensity = value;
  65. }
  66. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  67. {
  68. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  69. }
  70. int CTileInfo::getNearestObjectDistance() const
  71. {
  72. return nearestObjectDistance;
  73. }
  74. void CTileInfo::setNearestObjectDistance(int value)
  75. {
  76. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  77. }
  78. bool CTileInfo::shouldBeBlocked() const
  79. {
  80. return occupied == ETileType::BLOCKED;
  81. }
  82. bool CTileInfo::isBlocked() const
  83. {
  84. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  85. }
  86. bool CTileInfo::isPossible() const
  87. {
  88. return occupied == ETileType::POSSIBLE;
  89. }
  90. bool CTileInfo::isFree() const
  91. {
  92. return occupied == ETileType::FREE;
  93. }
  94. void CTileInfo::setOccupied(ETileType::ETileType value)
  95. {
  96. occupied = value;
  97. }
  98. ETerrainType CTileInfo::getTerrainType() const
  99. {
  100. return terrain;
  101. }
  102. void CTileInfo::setTerrainType(ETerrainType value)
  103. {
  104. terrain = value;
  105. }
  106. CRmgTemplateZone::CRmgTemplateZone() :
  107. id(0),
  108. type(ETemplateZoneType::PLAYER_START),
  109. size(1),
  110. townsAreSameType(false),
  111. matchTerrainToTown(true),
  112. townType(0),
  113. terrainType (ETerrainType::GRASS),
  114. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  115. totalDensity(0)
  116. {
  117. townTypes = getDefaultTownTypes();
  118. terrainTypes = getDefaultTerrainTypes();
  119. }
  120. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  121. {
  122. return id;
  123. }
  124. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  125. {
  126. if(value <= 0)
  127. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  128. id = value;
  129. }
  130. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  131. {
  132. return type;
  133. }
  134. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  135. {
  136. type = value;
  137. }
  138. int CRmgTemplateZone::getSize() const
  139. {
  140. return size;
  141. }
  142. void CRmgTemplateZone::setSize(int value)
  143. {
  144. if(value <= 0)
  145. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  146. size = value;
  147. }
  148. boost::optional<int> CRmgTemplateZone::getOwner() const
  149. {
  150. return owner;
  151. }
  152. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  153. {
  154. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  155. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  156. owner = value;
  157. }
  158. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  159. {
  160. return playerTowns;
  161. }
  162. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  163. {
  164. playerTowns = value;
  165. }
  166. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  167. {
  168. return neutralTowns;
  169. }
  170. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  171. {
  172. neutralTowns = value;
  173. }
  174. bool CRmgTemplateZone::getTownsAreSameType() const
  175. {
  176. return townsAreSameType;
  177. }
  178. void CRmgTemplateZone::setTownsAreSameType(bool value)
  179. {
  180. townsAreSameType = value;
  181. }
  182. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  183. {
  184. return townTypes;
  185. }
  186. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  187. {
  188. townTypes = value;
  189. }
  190. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  191. {
  192. std::set<TFaction> defaultTowns;
  193. auto towns = VLC->townh->getDefaultAllowed();
  194. for(int i = 0; i < towns.size(); ++i)
  195. {
  196. if(towns[i]) defaultTowns.insert(i);
  197. }
  198. return defaultTowns;
  199. }
  200. bool CRmgTemplateZone::getMatchTerrainToTown() const
  201. {
  202. return matchTerrainToTown;
  203. }
  204. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  205. {
  206. matchTerrainToTown = value;
  207. }
  208. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  209. {
  210. return terrainTypes;
  211. }
  212. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  213. {
  214. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  215. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  216. terrainTypes = value;
  217. }
  218. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  219. {
  220. std::set<ETerrainType> terTypes;
  221. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  222. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  223. for (auto & allowedTerType : allowedTerTypes)
  224. terTypes.insert(allowedTerType);
  225. return terTypes;
  226. }
  227. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  228. {
  229. mines[res] = amount;
  230. }
  231. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  232. {
  233. return mines;
  234. }
  235. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  236. {
  237. connections.push_back (otherZone);
  238. }
  239. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  240. {
  241. return connections;
  242. }
  243. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  244. {
  245. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  246. zoneMonsterStrength = val;
  247. }
  248. void CRmgTemplateZone::setTotalDensity (ui16 val)
  249. {
  250. totalDensity = val;
  251. }
  252. ui16 CRmgTemplateZone::getTotalDensity () const
  253. {
  254. return totalDensity;
  255. }
  256. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  257. {
  258. treasureInfo.push_back(info);
  259. }
  260. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  261. {
  262. return treasureInfo;
  263. }
  264. std::set<int3>* CRmgTemplateZone::getFreePaths()
  265. {
  266. return &freePaths;
  267. }
  268. float3 CRmgTemplateZone::getCenter() const
  269. {
  270. return center;
  271. }
  272. void CRmgTemplateZone::setCenter(const float3 &f)
  273. {
  274. //limit boundaries to (0,1) square
  275. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  276. }
  277. bool CRmgTemplateZone::pointIsIn(int x, int y)
  278. {
  279. return true;
  280. }
  281. int3 CRmgTemplateZone::getPos() const
  282. {
  283. return pos;
  284. }
  285. void CRmgTemplateZone::setPos(const int3 &Pos)
  286. {
  287. pos = Pos;
  288. }
  289. void CRmgTemplateZone::addTile (const int3 &pos)
  290. {
  291. tileinfo.insert(pos);
  292. }
  293. std::set<int3> CRmgTemplateZone::getTileInfo () const
  294. {
  295. return tileinfo;
  296. }
  297. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  298. {
  299. for (auto tile : tileinfo)
  300. {
  301. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  302. {
  303. if (!vstd::contains(this->tileinfo, pos))
  304. {
  305. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  306. {
  307. if (gen->isPossible(pos))
  308. gen->setOccupied (pos, ETileType::BLOCKED);
  309. });
  310. }
  311. });
  312. }
  313. }
  314. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  315. {
  316. std::vector<int3> clearedTiles;
  317. std::set<int3> possibleTiles;
  318. std::set<int3> tilesToClear; //will be set clear
  319. std::set<int3> tilesToIgnore; //will be erased in this iteration
  320. const float minDistance = std::sqrt(totalDensity);
  321. for (auto tile : tileinfo)
  322. {
  323. if (gen->isFree(tile))
  324. clearedTiles.push_back(tile);
  325. else if (gen->isPossible(tile))
  326. possibleTiles.insert(tile);
  327. }
  328. if (clearedTiles.empty()) //this should come from zone connections
  329. {
  330. clearedTiles.push_back(pos); //zone center should be always clear
  331. }
  332. while (possibleTiles.size())
  333. {
  334. for (auto tileToMakePath : possibleTiles)
  335. {
  336. //find closest free tile
  337. float currentDistance = 1e10;
  338. int3 closestTile (-1,-1,-1);
  339. for (auto clearTile : clearedTiles)
  340. {
  341. float distance = tileToMakePath.dist2d(clearTile);
  342. if (distance < currentDistance)
  343. {
  344. currentDistance = distance;
  345. closestTile = clearTile;
  346. }
  347. if (currentDistance <= minDistance)
  348. {
  349. //this tile is close enough. Forget about it and check next one
  350. tilesToIgnore.insert (tileToMakePath);
  351. break;
  352. }
  353. }
  354. //if tiles is not close enough, make path to it
  355. if (currentDistance > minDistance)
  356. {
  357. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  358. break; //next iteration - use already cleared tiles
  359. }
  360. }
  361. for (auto tileToClear : tilesToClear)
  362. {
  363. //move cleared tiles from one set to another
  364. clearedTiles.push_back(tileToClear);
  365. vstd::erase_if_present(possibleTiles, tileToClear);
  366. }
  367. for (auto tileToClear : tilesToIgnore)
  368. {
  369. //these tiles are already connected, ignore them
  370. vstd::erase_if_present(possibleTiles, tileToClear);
  371. }
  372. if (tilesToClear.empty()) //nothing else can be done (?)
  373. break;
  374. tilesToClear.clear(); //empty this container
  375. tilesToIgnore.clear();
  376. }
  377. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  378. }
  379. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  380. {
  381. /*
  382. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  383. do not leave zone border
  384. */
  385. bool result = false;
  386. bool end = false;
  387. int3 currentPos = src;
  388. float distance = currentPos.dist2dSQ (dst);
  389. while (!end)
  390. {
  391. if (currentPos == dst)
  392. {
  393. result = true;
  394. break;
  395. }
  396. auto lastDistance = distance;
  397. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  398. {
  399. if (!result) //not sure if lambda is worth it...
  400. {
  401. if (pos == dst)
  402. {
  403. result = true;
  404. end = true;
  405. }
  406. if (pos.dist2dSQ (dst) < distance)
  407. {
  408. if (!gen->isBlocked(pos))
  409. {
  410. if (vstd::contains (tileinfo, pos))
  411. {
  412. if (gen->isPossible(pos))
  413. {
  414. gen->setOccupied (pos, ETileType::FREE);
  415. if (clearedTiles)
  416. clearedTiles->insert(pos);
  417. currentPos = pos;
  418. distance = currentPos.dist2dSQ (dst);
  419. }
  420. else if (gen->isFree(pos))
  421. {
  422. end = true;
  423. result = true;
  424. }
  425. else
  426. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  427. }
  428. }
  429. }
  430. }
  431. });
  432. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  433. {
  434. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  435. break;
  436. }
  437. }
  438. return result;
  439. }
  440. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  441. {
  442. requiredObjects.push_back(std::make_pair(obj, strength));
  443. }
  444. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  445. {
  446. //precalculate actual (randomized) monster strength based on this post
  447. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  448. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  449. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  450. static const int value1[] = {2500, 1500, 1000, 500, 0};
  451. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  452. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  453. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  454. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  455. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  456. strength = strength1 + strength2;
  457. if (strength < 2000)
  458. return false; //no guard at all
  459. CreatureID creId = CreatureID::NONE;
  460. int amount = 0;
  461. std::vector<CreatureID> possibleCreatures;
  462. for (auto cre : VLC->creh->creatures)
  463. {
  464. if (cre->special)
  465. continue;
  466. 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
  467. {
  468. possibleCreatures.push_back(cre->idNumber);
  469. }
  470. }
  471. if (possibleCreatures.size())
  472. {
  473. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  474. amount = strength / VLC->creh->creatures[creId]->AIValue;
  475. if (amount >= 4)
  476. amount *= gen->rand.nextDouble(0.75, 1.25);
  477. }
  478. else //just pick any available creature
  479. {
  480. creId = CreatureID(132); //Azure Dragon
  481. amount = strength / VLC->creh->creatures[creId]->AIValue;
  482. }
  483. auto guard = new CGCreature();
  484. guard->ID = Obj::MONSTER;
  485. guard->subID = creId;
  486. auto hlp = new CStackInstance(creId, amount);
  487. //will be set during initialization
  488. guard->putStack(SlotID(0), hlp);
  489. placeObject(gen, guard, pos);
  490. return true;
  491. }
  492. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  493. {
  494. std::map<int3, CGObjectInstance *> treasures;
  495. std::set<int3> boundary;
  496. int3 guardPos (-1,-1,-1);
  497. int3 nextTreasurePos = pos;
  498. //default values
  499. int maxValue = 5000;
  500. int minValue = 1500;
  501. if (treasureInfo.size())
  502. {
  503. //roulette wheel
  504. int r = gen->rand.nextInt (1, totalDensity);
  505. for (auto t : treasureInfo)
  506. {
  507. if (r <= t.threshold)
  508. {
  509. maxValue = t.max;
  510. minValue = t.min;
  511. break;
  512. }
  513. }
  514. }
  515. int currentValue = 0;
  516. CGObjectInstance * object = nullptr;
  517. while (currentValue < minValue)
  518. {
  519. //TODO: this works only for 1-tile objects
  520. //make sure our shape is consistent
  521. treasures[nextTreasurePos] = nullptr;
  522. for (auto treasurePos : treasures)
  523. {
  524. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  525. {
  526. boundary.insert(pos);
  527. });
  528. }
  529. for (auto treasurePos : treasures)
  530. {
  531. //leaving only boundary around objects
  532. vstd::erase_if_present (boundary, treasurePos.first);
  533. }
  534. for (auto tile : boundary)
  535. {
  536. //we can't extend boundary anymore
  537. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  538. break;
  539. }
  540. int remaining = maxValue - currentValue;
  541. auto oi = getRandomObject(gen, remaining);
  542. object = oi.generateObject();
  543. if (!object)
  544. break;
  545. currentValue += oi.value;
  546. treasures[nextTreasurePos] = object;
  547. //now find place for next object
  548. int3 placeFound(-1,-1,-1);
  549. //FIXME: find out why teh following code causes crashes
  550. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  551. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  552. //for (auto tile : boundaryVec)
  553. for (auto tile : boundary)
  554. {
  555. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  556. {
  557. bool here = true;
  558. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  559. {
  560. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  561. here = false;
  562. });
  563. if (here)
  564. {
  565. placeFound = tile;
  566. break;
  567. }
  568. }
  569. }
  570. if (placeFound.valid())
  571. nextTreasurePos = placeFound;
  572. }
  573. if (treasures.size())
  574. {
  575. //find object closest to zone center, then con nect it to the middle of the zone
  576. int3 zoneCenter = getPos();
  577. int3 closestTile = int3(-1,-1,-1);
  578. float minDistance = 1e10;
  579. for (auto treasure : treasures)
  580. {
  581. if (zoneCenter.dist2d(treasure.first) < minDistance)
  582. {
  583. closestTile = treasure.first;
  584. minDistance = zoneCenter.dist2d(treasure.first);
  585. }
  586. }
  587. assert (closestTile.valid());
  588. if (!crunchPath (gen, closestTile, getPos(), id)) //make sure pile is connected to the middle of zone
  589. {
  590. for (auto treasure : treasures)
  591. {
  592. if (gen->isPossible(treasure.first))
  593. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  594. }
  595. return true;
  596. }
  597. for (auto tile : boundary) //guard must be standing there
  598. {
  599. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  600. {
  601. guardPos = tile;
  602. break;
  603. }
  604. }
  605. if (guardPos.valid())
  606. {
  607. for (auto treasure : treasures)
  608. {
  609. placeObject(gen, treasure.second, treasure.first - treasure.second->getVisitableOffset());
  610. }
  611. if (addMonster(gen, guardPos, currentValue))
  612. {//block only if the object is guarded
  613. for (auto tile : boundary)
  614. {
  615. if (gen->isPossible(tile))
  616. gen->setOccupied (tile, ETileType::BLOCKED);
  617. }
  618. }
  619. }
  620. else //we couldn't make a connection to this location, block it
  621. {
  622. for (auto treasure : treasures)
  623. {
  624. if (gen->isPossible(treasure.first))
  625. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  626. }
  627. }
  628. return true;
  629. }
  630. else //we did not place eveyrthing successfully
  631. return false;
  632. }
  633. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  634. {
  635. //FIXME: handle case that this player is not present -> towns should be set to neutral
  636. int totalTowns = 0;
  637. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  638. {
  639. //set zone types to player faction, generate main town
  640. logGlobal->infoStream() << "Preparing playing zone";
  641. int player_id = *owner - 1;
  642. auto & playerInfo = gen->map->players[player_id];
  643. if (playerInfo.canAnyonePlay())
  644. {
  645. PlayerColor player(player_id);
  646. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  647. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  648. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  649. auto town = new CGTownInstance();
  650. town->ID = Obj::TOWN;
  651. town->subID = townType;
  652. town->tempOwner = player;
  653. town->builtBuildings.insert(BuildingID::FORT);
  654. town->builtBuildings.insert(BuildingID::DEFAULT);
  655. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  656. totalTowns++;
  657. logGlobal->traceStream() << "Fill player info " << player_id;
  658. // Update player info
  659. playerInfo.allowedFactions.clear();
  660. playerInfo.allowedFactions.insert (townType);
  661. playerInfo.hasMainTown = true;
  662. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  663. playerInfo.generateHeroAtMainTown = true;
  664. //now create actual towns
  665. for (int i = 1; i < playerTowns.getCastleCount(); i++)
  666. {
  667. auto town = new CGTownInstance();
  668. town->ID = Obj::TOWN;
  669. if (townsAreSameType)
  670. town->subID = townType;
  671. else
  672. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  673. town->tempOwner = player;
  674. town->builtBuildings.insert(BuildingID::FORT);
  675. town->builtBuildings.insert(BuildingID::DEFAULT);
  676. addRequiredObject (town);
  677. totalTowns++;
  678. }
  679. for (int i = 0; i < playerTowns.getTownCount(); i++)
  680. {
  681. auto town = new CGTownInstance();
  682. town->ID = Obj::TOWN;
  683. if (townsAreSameType)
  684. town->subID = townType;
  685. else
  686. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  687. town->tempOwner = player;
  688. town->builtBuildings.insert(BuildingID::DEFAULT);
  689. addRequiredObject (town);
  690. totalTowns++;
  691. }
  692. //requiredObjects.push_back(town);
  693. }
  694. else
  695. {
  696. type = ETemplateZoneType::TREASURE;
  697. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  698. logGlobal->infoStream() << "Skipping this zone cause no player";
  699. }
  700. }
  701. else //no player
  702. {
  703. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  704. }
  705. for (int i = 0; i < neutralTowns.getCastleCount(); i++)
  706. {
  707. auto town = new CGTownInstance();
  708. town->ID = Obj::TOWN;
  709. if (townsAreSameType || totalTowns == 0) //first town must match zone type
  710. town->subID = townType;
  711. else
  712. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  713. town->tempOwner = PlayerColor::NEUTRAL;
  714. town->builtBuildings.insert(BuildingID::FORT);
  715. town->builtBuildings.insert(BuildingID::DEFAULT);
  716. if (!totalTowns) //first town in zone goes in the middle
  717. placeObject(gen, town, getPos() + town->getVisitableOffset());
  718. else
  719. addRequiredObject (town);
  720. totalTowns++;
  721. }
  722. for (int i = 0; i < neutralTowns.getTownCount(); i++)
  723. {
  724. auto town = new CGTownInstance();
  725. town->ID = Obj::TOWN;
  726. if (townsAreSameType || totalTowns == 0)
  727. town->subID = townType;
  728. else
  729. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  730. town->tempOwner = PlayerColor::NEUTRAL;
  731. town->builtBuildings.insert(BuildingID::DEFAULT);
  732. if (!totalTowns)
  733. placeObject(gen, town, getPos() + town->getVisitableOffset());
  734. else
  735. addRequiredObject (town);
  736. totalTowns++;
  737. }
  738. }
  739. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  740. {
  741. if (matchTerrainToTown)
  742. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  743. else
  744. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  745. //paint zone with matching terrain
  746. std::vector<int3> tiles;
  747. for (auto tile : tileinfo)
  748. {
  749. tiles.push_back (tile);
  750. }
  751. gen->editManager->getTerrainSelection().setSelection(tiles);
  752. gen->editManager->drawTerrain(terrainType, &gen->rand);
  753. }
  754. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  755. {
  756. std::vector<Res::ERes> required_mines;
  757. required_mines.push_back(Res::ERes::WOOD);
  758. required_mines.push_back(Res::ERes::ORE);
  759. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  760. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  761. //TODO: factory / copy constructor?
  762. for (const auto & res : woodOre)
  763. {
  764. //TODO: these 2 should be close to town (within 12 tiles radius)
  765. for (int i = 0; i < mines[res]; i++)
  766. {
  767. auto mine = new CGMine();
  768. mine->ID = Obj::MINE;
  769. mine->subID = static_cast<si32>(res);
  770. mine->producedResource = res;
  771. mine->producedQuantity = mine->defaultResProduction();
  772. addRequiredObject(mine, 1500);
  773. }
  774. }
  775. for (const auto & res : preciousResources)
  776. {
  777. for (int i = 0; i < mines[res]; i++)
  778. {
  779. auto mine = new CGMine();
  780. mine->ID = Obj::MINE;
  781. mine->subID = static_cast<si32>(res);
  782. mine->producedResource = res;
  783. mine->producedQuantity = mine->defaultResProduction();
  784. addRequiredObject(mine, 3500);
  785. }
  786. }
  787. for (int i = 0; i < mines[Res::GOLD]; i++)
  788. {
  789. auto mine = new CGMine();
  790. mine->ID = Obj::MINE;
  791. mine->subID = static_cast<si32>(Res::GOLD);
  792. mine->producedResource = Res::GOLD;
  793. mine->producedQuantity = mine->defaultResProduction();
  794. addRequiredObject(mine, 7000);
  795. }
  796. return true;
  797. }
  798. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  799. {
  800. logGlobal->infoStream() << "Creating required objects";
  801. for(const auto &obj : requiredObjects)
  802. {
  803. int3 pos;
  804. logGlobal->traceStream() << "Looking for place";
  805. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  806. {
  807. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  808. //TODO CLEANUP!
  809. return false;
  810. }
  811. logGlobal->traceStream() << "Place found";
  812. placeObject(gen, obj.first, pos);
  813. guardObject (gen, obj.first, obj.second);
  814. }
  815. return true;
  816. }
  817. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  818. {
  819. const double minDistance = 3;
  820. do {
  821. int3 pos;
  822. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  823. {
  824. break;
  825. }
  826. createTreasurePile (gen, pos);
  827. } while(true);
  828. }
  829. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  830. {
  831. //get all possible obstacles for this terrain
  832. for (auto primaryID : VLC->objtypeh->knownObjects())
  833. {
  834. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  835. {
  836. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  837. if (handler->isStaticObject())
  838. {
  839. for (auto temp : handler->getTemplates())
  840. {
  841. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  842. possibleObstacles.push_back(temp);
  843. }
  844. }
  845. }
  846. }
  847. auto sel = gen->editManager->getTerrainSelection();
  848. sel.clearSelection();
  849. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  850. {
  851. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  852. int3 obstaclePos = tile + temp.getBlockMapOffset();
  853. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  854. {
  855. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  856. placeObject(gen, obj, obstaclePos);
  857. return true;
  858. }
  859. return false;
  860. };
  861. for (auto tile : tileinfo)
  862. {
  863. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  864. {
  865. while (!tryToPlaceObstacleHere(tile));
  866. }
  867. else if (gen->isPossible(tile))
  868. {
  869. //try to place random obstacle once - if not possible, leave it clear
  870. tryToPlaceObstacleHere(tile);
  871. }
  872. }
  873. }
  874. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  875. {
  876. addAllPossibleObjects (gen);
  877. initTownType(gen);
  878. initTerrainType(gen);
  879. placeMines(gen);
  880. createRequiredObjects(gen);
  881. fractalize(gen); //after required objects are created and linked with their own paths
  882. createTreasures(gen);
  883. createObstacles(gen);
  884. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  885. return true;
  886. }
  887. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  888. {
  889. //si32 min_dist = sqrt(tileinfo.size()/density);
  890. int best_distance = 0;
  891. bool result = false;
  892. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  893. for(auto tile : tileinfo)
  894. {
  895. auto dist = gen->getTile(tile).getNearestObjectDistance();
  896. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  897. {
  898. bool allTilesAvailable = true;
  899. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  900. {
  901. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  902. {
  903. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  904. }
  905. });
  906. if (allTilesAvailable)
  907. {
  908. best_distance = dist;
  909. pos = tile;
  910. result = true;
  911. }
  912. }
  913. }
  914. if (result)
  915. {
  916. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  917. }
  918. return result;
  919. }
  920. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  921. {
  922. auto tilesBlockedByObject = temp.getBlockedOffsets();
  923. bool allTilesAvailable = true;
  924. for (auto blockingTile : tilesBlockedByObject)
  925. {
  926. int3 t = pos + blockingTile;
  927. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  928. {
  929. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  930. break;
  931. }
  932. }
  933. return allTilesAvailable;
  934. }
  935. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  936. {
  937. //we need object apperance to deduce free tiles
  938. if (obj->appearance.id == Obj::NO_OBJ)
  939. {
  940. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  941. if (templates.empty())
  942. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  943. obj->appearance = templates.front();
  944. }
  945. //si32 min_dist = sqrt(tileinfo.size()/density);
  946. int best_distance = 0;
  947. bool result = false;
  948. //si32 w = gen->map->width;
  949. //si32 h = gen->map->height;
  950. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  951. auto tilesBlockedByObject = obj->getBlockedOffsets();
  952. for (auto tile : tileinfo)
  953. {
  954. //object must be accessible from at least one surounding tile
  955. bool accessible = false;
  956. for (int x = -1; x < 2; x++)
  957. for (int y = -1; y <2; y++)
  958. {
  959. if (x && y) //check only if object is visitable from another tile
  960. {
  961. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  962. if (!vstd::contains(tilesBlockedByObject, offset))
  963. {
  964. int3 nearbyPos = tile + offset;
  965. if (gen->map->isInTheMap(nearbyPos))
  966. {
  967. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  968. accessible = true;
  969. }
  970. }
  971. }
  972. };
  973. if (!accessible)
  974. continue;
  975. auto ti = gen->getTile(tile);
  976. auto dist = ti.getNearestObjectDistance();
  977. //avoid borders
  978. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  979. {
  980. bool allTilesAvailable = true;
  981. for (auto blockingTile : tilesBlockedByObject)
  982. {
  983. int3 t = tile + blockingTile;
  984. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  985. {
  986. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  987. break;
  988. }
  989. }
  990. if (allTilesAvailable)
  991. {
  992. best_distance = dist;
  993. pos = tile;
  994. result = true;
  995. }
  996. }
  997. }
  998. if (result)
  999. {
  1000. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1001. }
  1002. return result;
  1003. }
  1004. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1005. {
  1006. if (!gen->map->isInTheMap(pos))
  1007. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  1008. object->pos = pos;
  1009. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1010. 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()));
  1011. for (auto tile : object->getBlockedPos())
  1012. {
  1013. if (!gen->map->isInTheMap(tile))
  1014. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1015. }
  1016. if (object->appearance.id == Obj::NO_OBJ)
  1017. {
  1018. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(gen->map->getTile(pos).terType);
  1019. if (templates.empty())
  1020. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  1021. object->appearance = templates.front();
  1022. }
  1023. gen->map->addBlockVisTiles(object);
  1024. gen->editManager->insertObject(object, pos);
  1025. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1026. }
  1027. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1028. {
  1029. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1030. checkAndPlaceObject (gen, object, pos);
  1031. auto points = object->getBlockedPos();
  1032. if (object->isVisitable())
  1033. points.insert(pos + object->getVisitableOffset());
  1034. points.insert(pos);
  1035. for(auto p : points)
  1036. {
  1037. if (gen->map->isInTheMap(p))
  1038. {
  1039. gen->setOccupied(p, ETileType::USED);
  1040. }
  1041. }
  1042. for(auto tile : tileinfo)
  1043. {
  1044. si32 d = pos.dist2d(tile);
  1045. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1046. }
  1047. }
  1048. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1049. {
  1050. //get all tiles from which this object can be accessed
  1051. int3 visitable = object->visitablePos();
  1052. std::vector<int3> tiles;
  1053. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1054. gen->foreach_neighbour(visitable, [&](int3& pos)
  1055. {
  1056. if (gen->isPossible(pos))
  1057. {
  1058. if (!vstd::contains(tilesBlockedByObject, pos))
  1059. {
  1060. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1061. {
  1062. tiles.push_back(pos);
  1063. }
  1064. }
  1065. };
  1066. });
  1067. return tiles;
  1068. }
  1069. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  1070. {
  1071. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1072. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1073. int3 guardTile(-1,-1,-1);
  1074. for (auto tile : tiles)
  1075. {
  1076. //crunching path may fail if center of teh zone is dirrectly over wide object
  1077. if (crunchPath (gen, tile, getPos(), id)) //make sure object is accessible before surrounding it with blocked tiles
  1078. {
  1079. guardTile = tile;
  1080. break;
  1081. }
  1082. }
  1083. if (!guardTile.valid())
  1084. {
  1085. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1086. return false;
  1087. }
  1088. if (addMonster (gen, guardTile, str)) //do not place obstacles around unguarded object
  1089. {
  1090. for (auto pos : tiles)
  1091. {
  1092. if (!gen->isFree(pos))
  1093. gen->setOccupied(pos, ETileType::BLOCKED);
  1094. }
  1095. gen->setOccupied (guardTile, ETileType::USED);
  1096. }
  1097. else //allow no guard or other object in front of this object
  1098. {
  1099. for (auto tile : tiles)
  1100. gen->setOccupied (tile, ETileType::FREE);
  1101. }
  1102. return true;
  1103. }
  1104. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  1105. {
  1106. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1107. ui32 total = 0;
  1108. ui32 minValue = 0.25f * value;
  1109. //roulette wheel
  1110. for (auto oi : possibleObjects)
  1111. {
  1112. if (oi.value >= minValue && oi.value <= value)
  1113. {
  1114. //TODO: check place for non-removable object
  1115. //problem: we need at least template for the object that does not yet exist
  1116. total += oi.probability;
  1117. tresholds.push_back (std::make_pair (total, oi));
  1118. }
  1119. }
  1120. //TODO: generate pandora box with gold if the value is very high
  1121. if (tresholds.empty())
  1122. {
  1123. ObjectInfo oi;
  1124. if (minValue > 20000) //we don't have object valuable enough
  1125. {
  1126. oi.generateObject = [minValue]() -> CGObjectInstance *
  1127. {
  1128. auto obj = new CGPandoraBox();
  1129. obj->ID = Obj::PANDORAS_BOX;
  1130. obj->subID = 0;
  1131. obj->resources[Res::GOLD] = minValue;
  1132. return obj;
  1133. };
  1134. oi.value = minValue;
  1135. oi.probability = 0;
  1136. }
  1137. else
  1138. {
  1139. oi.generateObject = [gen]() -> CGObjectInstance *
  1140. {
  1141. return nullptr;
  1142. };
  1143. oi.value = 0;
  1144. oi.probability = 0;
  1145. }
  1146. return oi;
  1147. }
  1148. int r = gen->rand.nextInt (1, total);
  1149. for (auto t : tresholds)
  1150. {
  1151. if (r <= t.first)
  1152. return t.second;
  1153. }
  1154. //FIXME: control reaches end of non-void function. Missing return?
  1155. }
  1156. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1157. {
  1158. //TODO: move typical objects to config
  1159. ObjectInfo oi;
  1160. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1161. for (int i = 0; i < 4; i++)
  1162. {
  1163. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1164. {
  1165. auto obj = new CGResource();
  1166. obj->ID = Obj::RESOURCE;
  1167. obj->subID = static_cast<si32>(preciousRes[i]);
  1168. obj->amount = 0;
  1169. return obj;
  1170. };
  1171. oi.value = 1400;
  1172. oi.probability = 300;
  1173. possibleObjects.push_back (oi);
  1174. }
  1175. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1176. for (int i = 0; i < 2; i++)
  1177. {
  1178. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1179. {
  1180. auto obj = new CGResource();
  1181. obj->ID = Obj::RESOURCE;
  1182. obj->subID = static_cast<si32>(woodOre[i]);
  1183. obj->amount = 0;
  1184. return obj;
  1185. };
  1186. oi.value = 1400;
  1187. oi.probability = 300;
  1188. possibleObjects.push_back (oi);
  1189. }
  1190. oi.generateObject = [gen]() -> CGObjectInstance *
  1191. {
  1192. auto obj = new CGResource();
  1193. obj->ID = Obj::RESOURCE;
  1194. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  1195. obj->amount = 0;
  1196. return obj;
  1197. };
  1198. oi.value = 750;
  1199. oi.probability = 300;
  1200. possibleObjects.push_back (oi);
  1201. oi.generateObject = [gen]() -> CGObjectInstance *
  1202. {
  1203. auto obj = new CGPickable();
  1204. obj->ID = Obj::TREASURE_CHEST;
  1205. obj->subID = 0;
  1206. return obj;
  1207. };
  1208. oi.value = 1500;
  1209. oi.probability = 1000;
  1210. possibleObjects.push_back (oi);
  1211. oi.generateObject = [gen]() -> CGObjectInstance *
  1212. {
  1213. auto obj = new CGArtifact();
  1214. obj->ID = Obj::RANDOM_TREASURE_ART;
  1215. obj->subID = 0;
  1216. auto a = new CArtifactInstance();
  1217. gen->map->addNewArtifactInstance(a);
  1218. obj->storedArtifact = a;
  1219. return obj;
  1220. };
  1221. oi.value = 2000;
  1222. oi.probability = 150;
  1223. possibleObjects.push_back (oi);
  1224. oi.generateObject = [gen]() -> CGObjectInstance *
  1225. {
  1226. auto obj = new CGArtifact();
  1227. obj->ID = Obj::RANDOM_MINOR_ART;
  1228. obj->subID = 0;
  1229. auto a = new CArtifactInstance();
  1230. gen->map->addNewArtifactInstance(a);
  1231. obj->storedArtifact = a;
  1232. return obj;
  1233. };
  1234. oi.value = 5000;
  1235. oi.probability = 150;
  1236. possibleObjects.push_back (oi);
  1237. oi.generateObject = [gen]() -> CGObjectInstance *
  1238. {
  1239. auto obj = new CGArtifact();
  1240. obj->ID = Obj::RANDOM_MAJOR_ART;
  1241. obj->subID = 0;
  1242. auto a = new CArtifactInstance();
  1243. gen->map->addNewArtifactInstance(a);
  1244. obj->storedArtifact = a;
  1245. return obj;
  1246. };
  1247. oi.value = 10000;
  1248. oi.probability = 150;
  1249. possibleObjects.push_back (oi);
  1250. oi.generateObject = [gen]() -> CGObjectInstance *
  1251. {
  1252. auto obj = new CGArtifact();
  1253. obj->ID = Obj::RANDOM_RELIC_ART;
  1254. obj->subID = 0;
  1255. auto a = new CArtifactInstance();
  1256. gen->map->addNewArtifactInstance(a);
  1257. obj->storedArtifact = a;
  1258. return obj;
  1259. };
  1260. oi.value = 20000;
  1261. oi.probability = 150;
  1262. possibleObjects.push_back (oi);
  1263. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1264. for (int i = 0; i < 5; i++)
  1265. {
  1266. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1267. {
  1268. auto obj = new CGArtifact();
  1269. obj->ID = Obj::SPELL_SCROLL;
  1270. obj->subID = 0;
  1271. std::vector<SpellID> out;
  1272. //TODO: unify with cb->getAllowedSpells?
  1273. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1274. {
  1275. const CSpell *spell = SpellID(i).toSpell();
  1276. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1277. {
  1278. out.push_back(spell->id);
  1279. }
  1280. }
  1281. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1282. gen->map->addNewArtifactInstance(a);
  1283. obj->storedArtifact = a;
  1284. return obj;
  1285. };
  1286. oi.value = scrollValues[i];
  1287. oi.probability = 30;
  1288. possibleObjects.push_back (oi);
  1289. }
  1290. //non-removable object for test
  1291. //oi.generateObject = [gen]() -> CGObjectInstance *
  1292. //{
  1293. // auto obj = new CGMagicWell();
  1294. // obj->ID = Obj::MAGIC_WELL;
  1295. // obj->subID = 0;
  1296. // return obj;
  1297. //};
  1298. //oi.value = 250;
  1299. //oi.probability = 100;
  1300. //possibleObjects.push_back (oi);
  1301. //oi.generateObject = [gen]() -> CGObjectInstance *
  1302. //{
  1303. // auto obj = new CGObelisk();
  1304. // obj->ID = Obj::OBELISK;
  1305. // obj->subID = 0;
  1306. // return obj;
  1307. //};
  1308. //oi.value = 3500;
  1309. //oi.probability = 200;
  1310. //possibleObjects.push_back (oi);
  1311. //oi.generateObject = [gen]() -> CGObjectInstance *
  1312. //{
  1313. // auto obj = new CBank();
  1314. // obj->ID = Obj::CREATURE_BANK;
  1315. // obj->subID = 5; //naga bank
  1316. // return obj;
  1317. //};
  1318. //oi.value = 3000;
  1319. //oi.probability = 100;
  1320. //possibleObjects.push_back (oi);
  1321. }