TreasurePlacer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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->getFaction() == 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->getFaction() == zone.getTownType())
  145. {
  146. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->getFaction()));
  147. oi.value = static_cast<ui32>(cre->getAIValue() * cre->getGrowth() * (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[EGameResID::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->getAIValue() || tierValues.empty()) //bug #2681
  224. return 0; //this box won't be generated
  225. //Follow the rules from https://heroes.thelazy.net/index.php/Pandora%27s_Box
  226. int actualTier = creature->getLevel() > tierValues.size() ?
  227. tierValues.size() - 1 :
  228. creature->getLevel() - 1;
  229. float creaturesAmount = std::floor((static_cast<float>(tierValues[actualTier])) / creature->getAIValue());
  230. if (creaturesAmount < 1)
  231. {
  232. return 0;
  233. }
  234. else if(creaturesAmount <= 5)
  235. {
  236. //No change
  237. }
  238. else if(creaturesAmount <= 12)
  239. {
  240. creaturesAmount = std::ceil(creaturesAmount / 2) * 2;
  241. }
  242. else if(creaturesAmount <= 50)
  243. {
  244. creaturesAmount = std::round(creaturesAmount / 5) * 5;
  245. }
  246. else
  247. {
  248. creaturesAmount = std::round(creaturesAmount / 10) * 10;
  249. }
  250. return static_cast<int>(creaturesAmount);
  251. };
  252. for(auto * creature : creatures)
  253. {
  254. int creaturesAmount = creatureToCount(creature);
  255. if(!creaturesAmount)
  256. continue;
  257. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  258. {
  259. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  260. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  261. auto * stack = new CStackInstance(creature, creaturesAmount);
  262. obj->creatures.putStack(SlotID(0), stack);
  263. return obj;
  264. };
  265. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  266. oi.value = static_cast<ui32>((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) / 3);
  267. oi.probability = 3;
  268. addObjectToRandomPool(oi);
  269. }
  270. //Pandora with 12 spells of certain level
  271. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  272. {
  273. oi.generateObject = [i, this]() -> CGObjectInstance *
  274. {
  275. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  276. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  277. std::vector <CSpell *> spells;
  278. for(auto spell : VLC->spellh->objects)
  279. {
  280. if(map.isAllowedSpell(spell->id) && spell->level == i)
  281. spells.push_back(spell);
  282. }
  283. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  284. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  285. {
  286. obj->spells.push_back(spells[j]->id);
  287. }
  288. return obj;
  289. };
  290. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  291. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  292. oi.probability = 2;
  293. addObjectToRandomPool(oi);
  294. }
  295. //Pandora with 15 spells of certain school
  296. for(int i = 0; i < 4; i++)
  297. {
  298. oi.generateObject = [i, this]() -> CGObjectInstance *
  299. {
  300. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  301. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  302. std::vector <CSpell *> spells;
  303. for(auto spell : VLC->spellh->objects)
  304. {
  305. if(map.isAllowedSpell(spell->id) && spell->school[SpellSchool(i)])
  306. spells.push_back(spell);
  307. }
  308. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  309. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  310. {
  311. obj->spells.push_back(spells[j]->id);
  312. }
  313. return obj;
  314. };
  315. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  316. oi.value = generator.getConfig().pandoraSpellSchool;
  317. oi.probability = 2;
  318. addObjectToRandomPool(oi);
  319. }
  320. // Pandora box with 60 random spells
  321. oi.generateObject = [this]() -> CGObjectInstance *
  322. {
  323. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  324. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  325. std::vector <CSpell *> spells;
  326. for(auto spell : VLC->spellh->objects)
  327. {
  328. if(map.isAllowedSpell(spell->id))
  329. spells.push_back(spell);
  330. }
  331. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  332. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  333. {
  334. obj->spells.push_back(spells[j]->id);
  335. }
  336. return obj;
  337. };
  338. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  339. oi.value = generator.getConfig().pandoraSpell60;
  340. oi.probability = 2;
  341. addObjectToRandomPool(oi);
  342. //seer huts with creatures or generic rewards
  343. if(questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  344. {
  345. static const int genericSeerHuts = 8;
  346. int seerHutsPerType = 0;
  347. const int questArtsRemaining = static_cast<int>(generator.getQuestArtsRemaning().size());
  348. //general issue is that not many artifact types are available for quests
  349. if(questArtsRemaining >= genericSeerHuts + static_cast<int>(creatures.size()))
  350. {
  351. seerHutsPerType = questArtsRemaining / (genericSeerHuts + static_cast<int>(creatures.size()));
  352. }
  353. else if(questArtsRemaining >= genericSeerHuts)
  354. {
  355. seerHutsPerType = 1;
  356. }
  357. oi.maxPerZone = seerHutsPerType;
  358. RandomGeneratorUtil::randomShuffle(creatures, generator.rand);
  359. auto generateArtInfo = [this](const ArtifactID & id) -> ObjectInfo
  360. {
  361. ObjectInfo artInfo;
  362. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  363. artInfo.maxPerZone = 1;
  364. artInfo.value = 2000; //treasure art
  365. artInfo.setTemplate(Obj::ARTIFACT, id, this->zone.getTerrainType());
  366. artInfo.generateObject = [id]() -> CGObjectInstance *
  367. {
  368. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  369. return handler->create(handler->getTemplates().front());
  370. };
  371. return artInfo;
  372. };
  373. for(int i = 0; i < std::min(static_cast<int>(creatures.size()), questArtsRemaining - genericSeerHuts); i++)
  374. {
  375. auto * creature = creatures[i];
  376. int creaturesAmount = creatureToCount(creature);
  377. if(!creaturesAmount)
  378. continue;
  379. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  380. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  381. {
  382. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  383. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  384. obj->rewardType = CGSeerHut::CREATURE;
  385. obj->rID = creature->getId();
  386. obj->rVal = creaturesAmount;
  387. obj->quest->missionType = CQuest::MISSION_ART;
  388. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  389. obj->quest->addArtifactID(artid);
  390. obj->quest->lastDay = -1;
  391. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  392. generator.banQuestArt(artid);
  393. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  394. return obj;
  395. };
  396. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  397. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) - 4000) / 3);
  398. oi.probability = 3;
  399. addObjectToRandomPool(oi);
  400. }
  401. static int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  402. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  403. {
  404. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  405. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  406. oi.value = generator.getConfig().questValues[i];
  407. oi.probability = 10;
  408. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  409. {
  410. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  411. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  412. obj->rewardType = CGSeerHut::EXPERIENCE;
  413. obj->rID = 0; //unitialized?
  414. obj->rVal = generator.getConfig().questRewardValues[i];
  415. obj->quest->missionType = CQuest::MISSION_ART;
  416. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  417. obj->quest->addArtifactID(artid);
  418. obj->quest->lastDay = -1;
  419. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  420. generator.banQuestArt(artid);
  421. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  422. return obj;
  423. };
  424. addObjectToRandomPool(oi);
  425. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  426. {
  427. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  428. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  429. obj->rewardType = CGSeerHut::RESOURCES;
  430. obj->rID = GameResID(EGameResID::GOLD);
  431. obj->rVal = generator.getConfig().questRewardValues[i];
  432. obj->quest->missionType = CQuest::MISSION_ART;
  433. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  434. obj->quest->addArtifactID(artid);
  435. obj->quest->lastDay = -1;
  436. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  437. generator.banQuestArt(artid);
  438. this->questArtZone->getModificator<TreasurePlacer>()->addObjectToRandomPool(generateArtInfo(artid));
  439. return obj;
  440. };
  441. addObjectToRandomPool(oi);
  442. }
  443. }
  444. }
  445. size_t TreasurePlacer::getPossibleObjectsSize() const
  446. {
  447. return possibleObjects.size();
  448. }
  449. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  450. {
  451. return zone.getType() != ETemplateZoneType::WATER && value > minGuardedValue;
  452. }
  453. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  454. {
  455. std::vector<ObjectInfo*> objectInfos;
  456. int maxValue = treasureInfo.max;
  457. int minValue = treasureInfo.min;
  458. const ui32 desiredValue = generator.rand.nextInt(minValue, maxValue);
  459. int currentValue = 0;
  460. bool hasLargeObject = false;
  461. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  462. {
  463. auto * oi = getRandomObject(desiredValue, currentValue, maxValue, !hasLargeObject);
  464. if(!oi) //fail
  465. break;
  466. if(oi->templ->isVisitableFromTop())
  467. {
  468. objectInfos.push_back(oi);
  469. }
  470. else
  471. {
  472. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  473. hasLargeObject = true;
  474. }
  475. //remove from possible objects
  476. assert(oi->maxPerZone);
  477. oi->maxPerZone--;
  478. currentValue += oi->value;
  479. }
  480. return objectInfos;
  481. }
  482. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  483. {
  484. rmg::Object rmgObject;
  485. for(const auto & oi : treasureInfos)
  486. {
  487. auto blockedArea = rmgObject.getArea();
  488. auto accessibleArea = rmgObject.getAccessibleArea();
  489. if(rmgObject.instances().empty())
  490. accessibleArea.add(int3());
  491. auto * object = oi->generateObject();
  492. object->appearance = oi->templ;
  493. auto & instance = rmgObject.addInstance(*object);
  494. do
  495. {
  496. if(accessibleArea.empty())
  497. {
  498. //fail - fallback
  499. rmgObject.clear();
  500. return rmgObject;
  501. }
  502. std::vector<int3> bestPositions;
  503. if(densePlacement)
  504. {
  505. int bestPositionsWeight = std::numeric_limits<int>::max();
  506. for(const auto & t : accessibleArea.getTilesVector())
  507. {
  508. instance.setPosition(t);
  509. int w = rmgObject.getAccessibleArea().getTilesVector().size();
  510. if(w < bestPositionsWeight)
  511. {
  512. bestPositions.clear();
  513. bestPositions.push_back(t);
  514. bestPositionsWeight = w;
  515. }
  516. else if(w == bestPositionsWeight)
  517. {
  518. bestPositions.push_back(t);
  519. }
  520. }
  521. }
  522. else
  523. {
  524. bestPositions = accessibleArea.getTilesVector();
  525. }
  526. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, generator.rand);
  527. instance.setPosition(nextPos - rmgObject.getPosition());
  528. auto instanceAccessibleArea = instance.getAccessibleArea();
  529. if(instance.getBlockedArea().getTilesVector().size() == 1)
  530. {
  531. if(instance.object().appearance->isVisitableFromTop() && instance.object().ID != Obj::CORPSE)
  532. instanceAccessibleArea.add(instance.getVisitablePosition());
  533. }
  534. //first object is good
  535. if(rmgObject.instances().size() == 1)
  536. break;
  537. //condition for good position
  538. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  539. break;
  540. //fail - new position
  541. accessibleArea.erase(nextPos);
  542. } while(true);
  543. }
  544. return rmgObject;
  545. }
  546. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, ui32 maxValue, bool allowLargeObjects)
  547. {
  548. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  549. ui32 total = 0;
  550. //calculate actual treasure value range based on remaining value
  551. ui32 maxVal = maxValue - currentValue;
  552. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  553. for(ObjectInfo & oi : possibleObjects) //copy constructor turned out to be costly
  554. {
  555. if(oi.value > maxVal)
  556. break; //this assumes values are sorted in ascending order
  557. if(!oi.templ->isVisitableFromTop() && !allowLargeObjects)
  558. continue;
  559. if(oi.value >= minValue && oi.maxPerZone > 0)
  560. {
  561. total += oi.probability;
  562. thresholds.emplace_back(total, &oi);
  563. }
  564. }
  565. if(thresholds.empty())
  566. {
  567. return nullptr;
  568. }
  569. else
  570. {
  571. int r = generator.rand.nextInt(1, total);
  572. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  573. {
  574. return static_cast<int>(rhs.first) < lhs;
  575. };
  576. //binary search = fastest
  577. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  578. return it->second;
  579. }
  580. }
  581. void TreasurePlacer::createTreasures(ObjectManager & manager)
  582. {
  583. const int maxAttempts = 2;
  584. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  585. int monsterStrength = zone.zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  586. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  587. minGuardedValue = minGuardedValues[monsterStrength];
  588. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  589. {
  590. return lhs.max > rhs.max;
  591. };
  592. auto restoreZoneLimits = [](const std::vector<ObjectInfo*> & treasurePile)
  593. {
  594. for(auto * oi : treasurePile)
  595. {
  596. oi->maxPerZone++;
  597. }
  598. };
  599. //place biggest treasures first at large distance, place smaller ones inbetween
  600. auto treasureInfo = zone.getTreasureInfo();
  601. boost::sort(treasureInfo, valueComparator);
  602. //sort treasures by ascending value so we can stop checking treasures with too high value
  603. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  604. {
  605. return oi1.value < oi2.value;
  606. });
  607. int totalDensity = 0;
  608. for (auto t : treasureInfo)
  609. {
  610. //discard objects with too high value to be ever placed
  611. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  612. {
  613. return oi.value > t.max;
  614. });
  615. totalDensity += t.density;
  616. //treasure density is inversely proportional to zone size but must be scaled back to map size
  617. //also, normalize it to zone count - higher count means relatively smaller zones
  618. //this is squared distance for optimization purposes
  619. const float minDistance = std::max<float>((125.f / totalDensity), 2.0f);
  620. //distance lower than 2 causes objects to overlap and crash
  621. for(int attempt = 0; attempt <= maxAttempts;)
  622. {
  623. auto treasurePileInfos = prepareTreasurePile(t);
  624. if(treasurePileInfos.empty())
  625. {
  626. ++attempt;
  627. continue;
  628. }
  629. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo * oi){return v + oi->value;});
  630. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  631. if(rmgObject.instances().empty()) //handle incorrect placement
  632. {
  633. restoreZoneLimits(treasurePileInfos);
  634. continue;
  635. }
  636. //guard treasure pile
  637. bool guarded = isGuardNeededForTreasure(value);
  638. if(guarded)
  639. guarded = manager.addGuard(rmgObject, value);
  640. auto possibleArea = zone.areaPossible();
  641. auto path = rmg::Path::invalid();
  642. if(guarded)
  643. {
  644. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3 & tile)
  645. {
  646. auto ti = map.getTile(tile);
  647. if(ti.getNearestObjectDistance() < minDistance)
  648. return -1.f;
  649. for(const auto & t : rmgObject.getArea().getTilesVector())
  650. {
  651. if(map.getTile(t).getNearestObjectDistance() < minDistance)
  652. return -1.f;
  653. }
  654. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  655. auto areaToBlock = rmgObject.getAccessibleArea(true);
  656. areaToBlock.subtract(guardedArea);
  657. if(areaToBlock.overlap(zone.freePaths()) || areaToBlock.overlap(manager.getVisitableArea()))
  658. return -1.f;
  659. return ti.getNearestObjectDistance();
  660. }, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  661. }
  662. else
  663. {
  664. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  665. }
  666. if(path.valid())
  667. {
  668. //debug purposes
  669. treasureArea.unite(rmgObject.getArea());
  670. if(guarded)
  671. {
  672. guards.unite(rmgObject.instances().back()->getBlockedArea());
  673. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  674. auto areaToBlock = rmgObject.getAccessibleArea(true);
  675. areaToBlock.subtract(guardedArea);
  676. treasureBlockArea.unite(areaToBlock);
  677. }
  678. zone.connectPath(path);
  679. manager.placeObject(rmgObject, guarded, true);
  680. attempt = 0;
  681. }
  682. else
  683. {
  684. restoreZoneLimits(treasurePileInfos);
  685. rmgObject.clear();
  686. ++attempt;
  687. }
  688. }
  689. }
  690. }
  691. char TreasurePlacer::dump(const int3 & t)
  692. {
  693. if(guards.contains(t))
  694. return '!';
  695. if(treasureArea.contains(t))
  696. return '$';
  697. if(treasureBlockArea.contains(t))
  698. return '*';
  699. return Modificator::dump(t);
  700. }
  701. void ObjectInfo::setTemplate(si32 type, si32 subtype, TerrainId terrainType)
  702. {
  703. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  704. if(!templHandler)
  705. return;
  706. auto templates = templHandler->getTemplates(terrainType);
  707. if(templates.empty())
  708. return;
  709. templ = templates.front();
  710. }
  711. VCMI_LIB_NAMESPACE_END