TreasurePlacer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. /*
  2. * TreasurePlacer.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 "TreasurePlacer.h"
  12. #include "CMapGenerator.h"
  13. #include "Functions.h"
  14. #include "ObjectManager.h"
  15. #include "RoadPlacer.h"
  16. #include "ConnectionsPlacer.h"
  17. #include "RmgMap.h"
  18. #include "TileInfo.h"
  19. #include "../mapObjects/CommonConstructors.h"
  20. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  21. #include "../CCreatureHandler.h"
  22. #include "../spells/CSpellHandler.h" //for choosing random spells
  23. #include "../mapping/CMap.h"
  24. #include "../mapping/CMapEditManager.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. void TreasurePlacer::process()
  27. {
  28. addAllPossibleObjects();
  29. auto * m = zone.getModificator<ObjectManager>();
  30. if(m)
  31. createTreasures(*m);
  32. }
  33. void TreasurePlacer::init()
  34. {
  35. DEPENDENCY(ObjectManager);
  36. DEPENDENCY(ConnectionsPlacer);
  37. POSTFUNCTION(RoadPlacer);
  38. }
  39. void TreasurePlacer::setQuestArtZone(Zone * otherZone)
  40. {
  41. questArtZone = otherZone;
  42. }
  43. void TreasurePlacer::addObjectToRandomPool(const ObjectInfo& oi)
  44. {
  45. possibleObjects.push_back(oi);
  46. }
  47. void TreasurePlacer::addAllPossibleObjects()
  48. {
  49. ObjectInfo oi;
  50. for(auto primaryID : VLC->objtypeh->knownObjects())
  51. {
  52. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  53. {
  54. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  55. if(!handler->isStaticObject() && handler->getRMGInfo().value)
  56. {
  57. auto rmgInfo = handler->getRMGInfo();
  58. if (rmgInfo.mapLimit || rmgInfo.value > zone.getMaxTreasureValue())
  59. {
  60. //Skip objects with per-map limit here
  61. continue;
  62. }
  63. auto templates = handler->getTemplates(zone.getTerrainType());
  64. if (templates.empty())
  65. continue;
  66. //Assume the template with fewest terrains is the most suitable
  67. auto temp = *boost::min_element(templates, [](std::shared_ptr<const ObjectTemplate> lhs, std::shared_ptr<const ObjectTemplate> rhs) -> bool
  68. {
  69. return lhs->getAllowedTerrains().size() < rhs->getAllowedTerrains().size();
  70. });
  71. oi.generateObject = [temp]() -> CGObjectInstance *
  72. {
  73. return VLC->objtypeh->getHandlerFor(temp->id, temp->subid)->create(temp);
  74. };
  75. oi.value = rmgInfo.value;
  76. oi.probability = rmgInfo.rarity;
  77. oi.templ = temp;
  78. oi.maxPerZone = rmgInfo.zoneLimit;
  79. addObjectToRandomPool(oi);
  80. }
  81. }
  82. }
  83. if(zone.getType() == ETemplateZoneType::WATER)
  84. return;
  85. //prisons
  86. //levels 1, 5, 10, 20, 30
  87. static int prisonsLevels = std::min(generator.getConfig().prisonExperience.size(), generator.getConfig().prisonValues.size());
  88. for(int i = 0; i < prisonsLevels; i++)
  89. {
  90. oi.generateObject = [i, this]() -> CGObjectInstance *
  91. {
  92. std::vector<ui32> possibleHeroes;
  93. for(int j = 0; j < map.map().allowedHeroes.size(); j++)
  94. {
  95. if(map.map().allowedHeroes[j])
  96. possibleHeroes.push_back(j);
  97. }
  98. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, generator.rand);
  99. auto factory = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0);
  100. auto * obj = dynamic_cast<CGHeroInstance *>(factory->create());
  101. obj->subID = hid; //will be initialized later
  102. obj->exp = generator.getConfig().prisonExperience[i];
  103. obj->setOwner(PlayerColor::NEUTRAL);
  104. map.map().allowedHeroes[hid] = false; //ban this hero
  105. generator.decreasePrisonsRemaining();
  106. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(zone.getTerrainType()).front(); //can't init template with hero subID
  107. return obj;
  108. };
  109. oi.setTemplate(Obj::PRISON, 0, zone.getTerrainType());
  110. oi.value = generator.getConfig().prisonValues[i];
  111. oi.probability = 30;
  112. oi.maxPerZone = generator.getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  113. addObjectToRandomPool(oi);
  114. }
  115. //all following objects are unlimited
  116. oi.maxPerZone = std::numeric_limits<ui32>::max();
  117. std::vector<CCreature *> creatures; //native creatures for this zone
  118. for(auto cre : VLC->creh->objects)
  119. {
  120. if(!cre->special && cre->faction == zone.getTownType())
  121. {
  122. creatures.push_back(cre);
  123. }
  124. }
  125. //dwellings
  126. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  127. for(auto dwellingType : dwellingTypes)
  128. {
  129. auto subObjects = VLC->objtypeh->knownSubObjects(dwellingType);
  130. if(dwellingType == Obj::CREATURE_GENERATOR1)
  131. {
  132. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  133. static int elementalConfluxROE[] = {7, 13, 16, 47};
  134. for(int & i : elementalConfluxROE)
  135. vstd::erase_if_present(subObjects, i);
  136. }
  137. for(auto secondaryID : subObjects)
  138. {
  139. const auto * dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  140. auto creatures = dwellingHandler->getProducedCreatures();
  141. if(creatures.empty())
  142. continue;
  143. const auto * cre = creatures.front();
  144. if(cre->faction == zone.getTownType())
  145. {
  146. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->faction));
  147. oi.value = static_cast<ui32>(cre->AIValue * cre->growth * (1 + (nativeZonesCount / map.getTotalZoneCount()) + (nativeZonesCount / 2)));
  148. oi.probability = 40;
  149. for(const auto & tmplate : dwellingHandler->getTemplates())
  150. {
  151. if(tmplate->canBePlacedAt(zone.getTerrainType()))
  152. {
  153. oi.generateObject = [tmplate, secondaryID, dwellingType]() -> CGObjectInstance *
  154. {
  155. auto * obj = VLC->objtypeh->getHandlerFor(dwellingType, secondaryID)->create(tmplate);
  156. obj->tempOwner = PlayerColor::NEUTRAL;
  157. return obj;
  158. };
  159. oi.templ = tmplate;
  160. addObjectToRandomPool(oi);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. for(int i = 0; i < generator.getConfig().scrollValues.size(); i++)
  167. {
  168. oi.generateObject = [i, this]() -> CGObjectInstance *
  169. {
  170. auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  171. auto * obj = dynamic_cast<CGArtifact *>(factory->create());
  172. std::vector<SpellID> out;
  173. for(auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  174. {
  175. if(map.isAllowedSpell(spell->id) && spell->level == i + 1)
  176. {
  177. out.push_back(spell->id);
  178. }
  179. }
  180. auto * a = CArtifactInstance::createScroll(*RandomGeneratorUtil::nextItem(out, generator.rand));
  181. obj->storedArtifact = a;
  182. return obj;
  183. };
  184. oi.setTemplate(Obj::SPELL_SCROLL, 0, zone.getTerrainType());
  185. oi.value = generator.getConfig().scrollValues[i];
  186. oi.probability = 30;
  187. addObjectToRandomPool(oi);
  188. }
  189. //pandora box with gold
  190. for(int i = 1; i < 5; i++)
  191. {
  192. oi.generateObject = [i]() -> CGObjectInstance *
  193. {
  194. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  195. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  196. obj->resources[Res::GOLD] = i * 5000;
  197. return obj;
  198. };
  199. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  200. oi.value = i * generator.getConfig().pandoraMultiplierGold;
  201. oi.probability = 5;
  202. addObjectToRandomPool(oi);
  203. }
  204. //pandora box with experience
  205. for(int i = 1; i < 5; i++)
  206. {
  207. oi.generateObject = [i]() -> CGObjectInstance *
  208. {
  209. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  210. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  211. obj->gainedExp = i * 5000;
  212. return obj;
  213. };
  214. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  215. oi.value = i * generator.getConfig().pandoraMultiplierExperience;
  216. oi.probability = 20;
  217. addObjectToRandomPool(oi);
  218. }
  219. //pandora box with creatures
  220. const std::vector<int> & tierValues = generator.getConfig().pandoraCreatureValues;
  221. auto creatureToCount = [tierValues](CCreature * creature) -> int
  222. {
  223. if(!creature->AIValue || tierValues.empty()) //bug #2681
  224. return 0; //this box won't be generated
  225. int actualTier = creature->level > tierValues.size() ?
  226. tierValues.size() - 1 :
  227. creature->level - 1;
  228. float creaturesAmount = (static_cast<float>(tierValues[actualTier])) / creature->AIValue;
  229. if(creaturesAmount <= 5)
  230. {
  231. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  232. if(creaturesAmount < 1)
  233. return 0;
  234. }
  235. else if(creaturesAmount <= 12)
  236. {
  237. (creaturesAmount /= 2) *= 2;
  238. }
  239. else if(creaturesAmount <= 50)
  240. {
  241. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  242. }
  243. else
  244. {
  245. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  246. }
  247. return static_cast<int>(creaturesAmount);
  248. };
  249. for(auto * creature : creatures)
  250. {
  251. int creaturesAmount = creatureToCount(creature);
  252. if(!creaturesAmount)
  253. continue;
  254. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  255. {
  256. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  257. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  258. auto * stack = new CStackInstance(creature, creaturesAmount);
  259. obj->creatures.putStack(SlotID(0), stack);
  260. return obj;
  261. };
  262. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  263. oi.value = static_cast<ui32>((2 * (creature->AIValue) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->faction)) / map.getTotalZoneCount())) / 3);
  264. oi.probability = 3;
  265. addObjectToRandomPool(oi);
  266. }
  267. //Pandora with 12 spells of certain level
  268. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  269. {
  270. oi.generateObject = [i, this]() -> CGObjectInstance *
  271. {
  272. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  273. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  274. std::vector <CSpell *> spells;
  275. for(auto spell : VLC->spellh->objects)
  276. {
  277. if(map.isAllowedSpell(spell->id) && spell->level == i)
  278. spells.push_back(spell);
  279. }
  280. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  281. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  282. {
  283. obj->spells.push_back(spells[j]->id);
  284. }
  285. return obj;
  286. };
  287. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  288. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  289. oi.probability = 2;
  290. addObjectToRandomPool(oi);
  291. }
  292. //Pandora with 15 spells of certain school
  293. for(int i = 0; i < 4; i++)
  294. {
  295. oi.generateObject = [i, this]() -> CGObjectInstance *
  296. {
  297. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  298. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  299. std::vector <CSpell *> spells;
  300. for(auto spell : VLC->spellh->objects)
  301. {
  302. if(map.isAllowedSpell(spell->id) && spell->school[static_cast<ESpellSchool>(i)])
  303. spells.push_back(spell);
  304. }
  305. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  306. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  307. {
  308. obj->spells.push_back(spells[j]->id);
  309. }
  310. return obj;
  311. };
  312. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  313. oi.value = generator.getConfig().pandoraSpellSchool;
  314. oi.probability = 2;
  315. addObjectToRandomPool(oi);
  316. }
  317. // Pandora box with 60 random spells
  318. oi.generateObject = [this]() -> CGObjectInstance *
  319. {
  320. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  321. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  322. std::vector <CSpell *> spells;
  323. for(auto spell : VLC->spellh->objects)
  324. {
  325. if(map.isAllowedSpell(spell->id))
  326. spells.push_back(spell);
  327. }
  328. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  329. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  330. {
  331. obj->spells.push_back(spells[j]->id);
  332. }
  333. return obj;
  334. };
  335. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  336. oi.value = generator.getConfig().pandoraSpell60;
  337. oi.probability = 2;
  338. addObjectToRandomPool(oi);
  339. //seer huts with creatures or generic rewards
  340. if(questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  341. {
  342. static const int genericSeerHuts = 8;
  343. int seerHutsPerType = 0;
  344. const int questArtsRemaining = static_cast<int>(generator.getQuestArtsRemaning().size());
  345. //general issue is that not many artifact types are available for quests
  346. if(questArtsRemaining >= genericSeerHuts + static_cast<int>(creatures.size()))
  347. {
  348. seerHutsPerType = questArtsRemaining / (genericSeerHuts + static_cast<int>(creatures.size()));
  349. }
  350. else if(questArtsRemaining >= genericSeerHuts)
  351. {
  352. seerHutsPerType = 1;
  353. }
  354. oi.maxPerZone = seerHutsPerType;
  355. RandomGeneratorUtil::randomShuffle(creatures, generator.rand);
  356. auto generateArtInfo = [this](const ArtifactID & id) -> ObjectInfo
  357. {
  358. ObjectInfo artInfo;
  359. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  360. artInfo.maxPerZone = 1;
  361. artInfo.value = 2000; //treasure art
  362. artInfo.setTemplate(Obj::ARTIFACT, id, this->zone.getTerrainType());
  363. artInfo.generateObject = [id]() -> CGObjectInstance *
  364. {
  365. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  366. return handler->create(handler->getTemplates().front());
  367. };
  368. return artInfo;
  369. };
  370. for(int i = 0; i < std::min(static_cast<int>(creatures.size()), questArtsRemaining - genericSeerHuts); i++)
  371. {
  372. auto * creature = creatures[i];
  373. int creaturesAmount = creatureToCount(creature);
  374. if(!creaturesAmount)
  375. continue;
  376. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  377. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  378. {
  379. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  380. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  381. obj->rewardType = CGSeerHut::CREATURE;
  382. obj->rID = creature->idNumber;
  383. obj->rVal = creaturesAmount;
  384. obj->quest->missionType = CQuest::MISSION_ART;
  385. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  386. obj->quest->addArtifactID(artid);
  387. obj->quest->lastDay = -1;
  388. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  389. generator.banQuestArt(artid);
  390. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  391. return obj;
  392. };
  393. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  394. oi.value = static_cast<ui32>(((2 * (creature->AIValue) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->faction)) / map.getTotalZoneCount())) - 4000) / 3);
  395. oi.probability = 3;
  396. addObjectToRandomPool(oi);
  397. }
  398. static int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  399. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  400. {
  401. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  402. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  403. oi.value = generator.getConfig().questValues[i];
  404. oi.probability = 10;
  405. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  406. {
  407. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  408. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  409. obj->rewardType = CGSeerHut::EXPERIENCE;
  410. obj->rID = 0; //unitialized?
  411. obj->rVal = generator.getConfig().questRewardValues[i];
  412. obj->quest->missionType = CQuest::MISSION_ART;
  413. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  414. obj->quest->addArtifactID(artid);
  415. obj->quest->lastDay = -1;
  416. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  417. generator.banQuestArt(artid);
  418. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  419. return obj;
  420. };
  421. addObjectToRandomPool(oi);
  422. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  423. {
  424. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  425. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  426. obj->rewardType = CGSeerHut::RESOURCES;
  427. obj->rID = Res::GOLD;
  428. obj->rVal = generator.getConfig().questRewardValues[i];
  429. obj->quest->missionType = CQuest::MISSION_ART;
  430. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  431. obj->quest->addArtifactID(artid);
  432. obj->quest->lastDay = -1;
  433. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  434. generator.banQuestArt(artid);
  435. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  436. return obj;
  437. };
  438. addObjectToRandomPool(oi);
  439. }
  440. }
  441. }
  442. size_t TreasurePlacer::getPossibleObjectsSize() const
  443. {
  444. return possibleObjects.size();
  445. }
  446. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  447. {
  448. return zone.getType() != ETemplateZoneType::WATER && value > minGuardedValue;
  449. }
  450. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  451. {
  452. std::vector<ObjectInfo*> objectInfos;
  453. int maxValue = treasureInfo.max;
  454. int minValue = treasureInfo.min;
  455. const ui32 desiredValue = generator.rand.nextInt(minValue, maxValue);
  456. int currentValue = 0;
  457. bool hasLargeObject = false;
  458. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  459. {
  460. auto * oi = getRandomObject(desiredValue, currentValue, maxValue, !hasLargeObject);
  461. if(!oi) //fail
  462. break;
  463. if(oi->templ->isVisitableFromTop())
  464. {
  465. objectInfos.push_back(oi);
  466. }
  467. else
  468. {
  469. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  470. hasLargeObject = true;
  471. }
  472. //remove from possible objects
  473. assert(oi->maxPerZone);
  474. oi->maxPerZone--;
  475. currentValue += oi->value;
  476. }
  477. return objectInfos;
  478. }
  479. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  480. {
  481. rmg::Object rmgObject;
  482. for(const auto & oi : treasureInfos)
  483. {
  484. auto blockedArea = rmgObject.getArea();
  485. auto accessibleArea = rmgObject.getAccessibleArea();
  486. if(rmgObject.instances().empty())
  487. accessibleArea.add(int3());
  488. auto * object = oi->generateObject();
  489. object->appearance = oi->templ;
  490. auto & instance = rmgObject.addInstance(*object);
  491. do
  492. {
  493. if(accessibleArea.empty())
  494. {
  495. //fail - fallback
  496. rmgObject.clear();
  497. return rmgObject;
  498. }
  499. std::vector<int3> bestPositions;
  500. if(densePlacement)
  501. {
  502. int bestPositionsWeight = std::numeric_limits<int>::max();
  503. for(const auto & t : accessibleArea.getTilesVector())
  504. {
  505. instance.setPosition(t);
  506. int w = rmgObject.getAccessibleArea().getTilesVector().size();
  507. if(w < bestPositionsWeight)
  508. {
  509. bestPositions.clear();
  510. bestPositions.push_back(t);
  511. bestPositionsWeight = w;
  512. }
  513. else if(w == bestPositionsWeight)
  514. {
  515. bestPositions.push_back(t);
  516. }
  517. }
  518. }
  519. else
  520. {
  521. bestPositions = accessibleArea.getTilesVector();
  522. }
  523. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, generator.rand);
  524. instance.setPosition(nextPos - rmgObject.getPosition());
  525. auto instanceAccessibleArea = instance.getAccessibleArea();
  526. if(instance.getBlockedArea().getTilesVector().size() == 1)
  527. {
  528. if(instance.object().appearance->isVisitableFromTop() && instance.object().ID != Obj::CORPSE)
  529. instanceAccessibleArea.add(instance.getVisitablePosition());
  530. }
  531. //first object is good
  532. if(rmgObject.instances().size() == 1)
  533. break;
  534. //condition for good position
  535. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  536. break;
  537. //fail - new position
  538. accessibleArea.erase(nextPos);
  539. } while(true);
  540. }
  541. return rmgObject;
  542. }
  543. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, ui32 maxValue, bool allowLargeObjects)
  544. {
  545. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  546. ui32 total = 0;
  547. //calculate actual treasure value range based on remaining value
  548. ui32 maxVal = maxValue - currentValue;
  549. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  550. for(ObjectInfo & oi : possibleObjects) //copy constructor turned out to be costly
  551. {
  552. if(oi.value > maxVal)
  553. break; //this assumes values are sorted in ascending order
  554. if(!oi.templ->isVisitableFromTop() && !allowLargeObjects)
  555. continue;
  556. if(oi.value >= minValue && oi.maxPerZone > 0)
  557. {
  558. total += oi.probability;
  559. thresholds.emplace_back(total, &oi);
  560. }
  561. }
  562. if(thresholds.empty())
  563. {
  564. return nullptr;
  565. }
  566. else
  567. {
  568. int r = generator.rand.nextInt(1, total);
  569. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  570. {
  571. return static_cast<int>(rhs.first) < lhs;
  572. };
  573. //binary search = fastest
  574. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  575. return it->second;
  576. }
  577. }
  578. void TreasurePlacer::createTreasures(ObjectManager & manager)
  579. {
  580. const int maxAttempts = 2;
  581. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  582. int monsterStrength = zone.zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  583. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  584. minGuardedValue = minGuardedValues[monsterStrength];
  585. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  586. {
  587. return lhs.max > rhs.max;
  588. };
  589. auto restoreZoneLimits = [](const std::vector<ObjectInfo*> & treasurePile)
  590. {
  591. for(auto * oi : treasurePile)
  592. {
  593. oi->maxPerZone++;
  594. }
  595. };
  596. //place biggest treasures first at large distance, place smaller ones inbetween
  597. auto treasureInfo = zone.getTreasureInfo();
  598. boost::sort(treasureInfo, valueComparator);
  599. //sort treasures by ascending value so we can stop checking treasures with too high value
  600. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  601. {
  602. return oi1.value < oi2.value;
  603. });
  604. int totalDensity = 0;
  605. for (auto t : treasureInfo)
  606. {
  607. //discard objects with too high value to be ever placed
  608. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  609. {
  610. return oi.value > t.max;
  611. });
  612. totalDensity += t.density;
  613. //treasure density is inversely proportional to zone size but must be scaled back to map size
  614. //also, normalize it to zone count - higher count means relatively smaller zones
  615. //this is squared distance for optimization purposes
  616. const float minDistance = std::max<float>((125.f / totalDensity), 2.0f);
  617. //distance lower than 2 causes objects to overlap and crash
  618. for(int attempt = 0; attempt <= maxAttempts;)
  619. {
  620. auto treasurePileInfos = prepareTreasurePile(t);
  621. if(treasurePileInfos.empty())
  622. {
  623. ++attempt;
  624. continue;
  625. }
  626. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo * oi){return v + oi->value;});
  627. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  628. if(rmgObject.instances().empty()) //handle incorrect placement
  629. {
  630. restoreZoneLimits(treasurePileInfos);
  631. continue;
  632. }
  633. //guard treasure pile
  634. bool guarded = isGuardNeededForTreasure(value);
  635. if(guarded)
  636. guarded = manager.addGuard(rmgObject, value);
  637. auto possibleArea = zone.areaPossible();
  638. auto path = rmg::Path::invalid();
  639. if(guarded)
  640. {
  641. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3 & tile)
  642. {
  643. auto ti = map.getTile(tile);
  644. if(ti.getNearestObjectDistance() < minDistance)
  645. return -1.f;
  646. for(const auto & t : rmgObject.getArea().getTilesVector())
  647. {
  648. if(map.getTile(t).getNearestObjectDistance() < minDistance)
  649. return -1.f;
  650. }
  651. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  652. auto areaToBlock = rmgObject.getAccessibleArea(true);
  653. areaToBlock.subtract(guardedArea);
  654. if(areaToBlock.overlap(zone.freePaths()) || areaToBlock.overlap(manager.getVisitableArea()))
  655. return -1.f;
  656. return ti.getNearestObjectDistance();
  657. }, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  658. }
  659. else
  660. {
  661. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  662. }
  663. if(path.valid())
  664. {
  665. //debug purposes
  666. treasureArea.unite(rmgObject.getArea());
  667. if(guarded)
  668. {
  669. guards.unite(rmgObject.instances().back()->getBlockedArea());
  670. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  671. auto areaToBlock = rmgObject.getAccessibleArea(true);
  672. areaToBlock.subtract(guardedArea);
  673. treasureBlockArea.unite(areaToBlock);
  674. }
  675. zone.connectPath(path);
  676. manager.placeObject(rmgObject, guarded, true);
  677. attempt = 0;
  678. }
  679. else
  680. {
  681. restoreZoneLimits(treasurePileInfos);
  682. rmgObject.clear();
  683. ++attempt;
  684. }
  685. }
  686. }
  687. }
  688. char TreasurePlacer::dump(const int3 & t)
  689. {
  690. if(guards.contains(t))
  691. return '!';
  692. if(treasureArea.contains(t))
  693. return '$';
  694. if(treasureBlockArea.contains(t))
  695. return '*';
  696. return Modificator::dump(t);
  697. }
  698. void ObjectInfo::setTemplate(si32 type, si32 subtype, TerrainId terrainType)
  699. {
  700. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  701. if(!templHandler)
  702. return;
  703. auto templates = templHandler->getTemplates(terrainType);
  704. if(templates.empty())
  705. return;
  706. templ = templates.front();
  707. }
  708. VCMI_LIB_NAMESPACE_END