TreasurePlacer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 "../CZonePlacer.h"
  20. #include "QuestArtifactPlacer.h"
  21. #include "../../ArtifactUtils.h"
  22. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  23. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  24. #include "../../mapObjectConstructors/DwellingInstanceConstructor.h"
  25. #include "../../mapObjects/CGHeroInstance.h"
  26. #include "../../mapObjects/CGPandoraBox.h"
  27. #include "../../CCreatureHandler.h"
  28. #include "../../spells/CSpellHandler.h" //for choosing random spells
  29. #include "../../mapping/CMap.h"
  30. #include "../../mapping/CMapEditManager.h"
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void TreasurePlacer::process()
  33. {
  34. addAllPossibleObjects();
  35. auto * m = zone.getModificator<ObjectManager>();
  36. if(m)
  37. createTreasures(*m);
  38. }
  39. void TreasurePlacer::init()
  40. {
  41. maxPrisons = 0; //Should be in the constructor, but we use macro for that
  42. DEPENDENCY(ObjectManager);
  43. DEPENDENCY(ConnectionsPlacer);
  44. POSTFUNCTION(RoadPlacer);
  45. }
  46. void TreasurePlacer::addObjectToRandomPool(const ObjectInfo& oi)
  47. {
  48. RecursiveLock lock(externalAccessMutex);
  49. possibleObjects.push_back(oi);
  50. }
  51. void TreasurePlacer::addAllPossibleObjects()
  52. {
  53. ObjectInfo oi;
  54. for(auto primaryID : VLC->objtypeh->knownObjects())
  55. {
  56. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  57. {
  58. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  59. if(!handler->isStaticObject() && handler->getRMGInfo().value)
  60. {
  61. auto rmgInfo = handler->getRMGInfo();
  62. if (rmgInfo.mapLimit || rmgInfo.value > zone.getMaxTreasureValue())
  63. {
  64. //Skip objects with per-map limit here
  65. continue;
  66. }
  67. oi.generateObject = [primaryID, secondaryID]() -> CGObjectInstance *
  68. {
  69. return VLC->objtypeh->getHandlerFor(primaryID, secondaryID)->create();
  70. };
  71. oi.value = rmgInfo.value;
  72. oi.probability = rmgInfo.rarity;
  73. oi.setTemplates(primaryID, secondaryID, zone.getTerrainType());
  74. oi.maxPerZone = rmgInfo.zoneLimit;
  75. if(!oi.templates.empty())
  76. addObjectToRandomPool(oi);
  77. }
  78. }
  79. }
  80. //Generate Prison on water only if it has a template
  81. auto prisonTemplates = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(zone.getTerrainType());
  82. if (!prisonTemplates.empty())
  83. {
  84. //prisons
  85. //levels 1, 5, 10, 20, 30
  86. static int prisonsLevels = std::min(generator.getConfig().prisonExperience.size(), generator.getConfig().prisonValues.size());
  87. size_t prisonsLeft = getMaxPrisons();
  88. for (int i = prisonsLevels - 1; i >= 0; i--)
  89. {
  90. oi.value = generator.getConfig().prisonValues[i];
  91. if (oi.value > zone.getMaxTreasureValue())
  92. {
  93. continue;
  94. }
  95. oi.generateObject = [i, this]() -> CGObjectInstance*
  96. {
  97. auto possibleHeroes = generator.getAllPossibleHeroes();
  98. HeroTypeID hid = *RandomGeneratorUtil::nextItem(possibleHeroes, zone.getRand());
  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. generator.banHero(hid);
  105. return obj;
  106. };
  107. oi.setTemplates(Obj::PRISON, 0, zone.getTerrainType());
  108. oi.value = generator.getConfig().prisonValues[i];
  109. oi.probability = 30;
  110. //Distribute all allowed prisons, starting from the most valuable
  111. oi.maxPerZone = (std::ceil((float)prisonsLeft / (i + 1)));
  112. prisonsLeft -= oi.maxPerZone;
  113. if(!oi.templates.empty())
  114. addObjectToRandomPool(oi);
  115. }
  116. }
  117. if(zone.getType() == ETemplateZoneType::WATER)
  118. return;
  119. //all following objects are unlimited
  120. oi.maxPerZone = std::numeric_limits<ui32>::max();
  121. std::vector<CCreature *> creatures; //native creatures for this zone
  122. for(auto cre : VLC->creh->objects)
  123. {
  124. if(!cre->special && cre->getFaction() == zone.getTownType())
  125. {
  126. creatures.push_back(cre);
  127. }
  128. }
  129. //dwellings
  130. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  131. for(auto dwellingType : dwellingTypes)
  132. {
  133. auto subObjects = VLC->objtypeh->knownSubObjects(dwellingType);
  134. if(dwellingType == Obj::CREATURE_GENERATOR1)
  135. {
  136. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  137. static int elementalConfluxROE[] = {7, 13, 16, 47};
  138. for(int & i : elementalConfluxROE)
  139. vstd::erase_if_present(subObjects, i);
  140. }
  141. for(auto secondaryID : subObjects)
  142. {
  143. const auto * dwellingHandler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  144. auto creatures = dwellingHandler->getProducedCreatures();
  145. if(creatures.empty())
  146. continue;
  147. const auto * cre = creatures.front();
  148. if(cre->getFaction() == zone.getTownType())
  149. {
  150. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->getFaction()));
  151. oi.value = static_cast<ui32>(cre->getAIValue() * cre->getGrowth() * (1 + (nativeZonesCount / map.getTotalZoneCount()) + (nativeZonesCount / 2)));
  152. oi.probability = 40;
  153. oi.generateObject = [secondaryID, dwellingType]() -> CGObjectInstance *
  154. {
  155. auto * obj = VLC->objtypeh->getHandlerFor(dwellingType, secondaryID)->create();
  156. obj->tempOwner = PlayerColor::NEUTRAL;
  157. return obj;
  158. };
  159. oi.setTemplates(dwellingType, secondaryID, zone.getTerrainType());
  160. if(!oi.templates.empty())
  161. addObjectToRandomPool(oi);
  162. }
  163. }
  164. }
  165. for(int i = 0; i < generator.getConfig().scrollValues.size(); i++)
  166. {
  167. oi.generateObject = [i, this]() -> CGObjectInstance *
  168. {
  169. auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  170. auto * obj = dynamic_cast<CGArtifact *>(factory->create());
  171. std::vector<SpellID> out;
  172. for(auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  173. {
  174. if(map.isAllowedSpell(spell->id) && spell->getLevel() == i + 1)
  175. {
  176. out.push_back(spell->id);
  177. }
  178. }
  179. auto * a = ArtifactUtils::createScroll(*RandomGeneratorUtil::nextItem(out, zone.getRand()));
  180. obj->storedArtifact = a;
  181. return obj;
  182. };
  183. oi.setTemplates(Obj::SPELL_SCROLL, 0, zone.getTerrainType());
  184. oi.value = generator.getConfig().scrollValues[i];
  185. oi.probability = 30;
  186. if(!oi.templates.empty())
  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. Rewardable::VisitInfo reward;
  197. reward.reward.resources[EGameResID::GOLD] = i * 5000;
  198. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  199. obj->configuration.info.push_back(reward);
  200. return obj;
  201. };
  202. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  203. oi.value = i * generator.getConfig().pandoraMultiplierGold;
  204. oi.probability = 5;
  205. if(!oi.templates.empty())
  206. addObjectToRandomPool(oi);
  207. }
  208. //pandora box with experience
  209. for(int i = 1; i < 5; i++)
  210. {
  211. oi.generateObject = [i]() -> CGObjectInstance *
  212. {
  213. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  214. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  215. Rewardable::VisitInfo reward;
  216. reward.reward.heroExperience = i * 5000;
  217. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  218. obj->configuration.info.push_back(reward);
  219. return obj;
  220. };
  221. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  222. oi.value = i * generator.getConfig().pandoraMultiplierExperience;
  223. oi.probability = 20;
  224. if(!oi.templates.empty())
  225. addObjectToRandomPool(oi);
  226. }
  227. //pandora box with creatures
  228. const std::vector<int> & tierValues = generator.getConfig().pandoraCreatureValues;
  229. auto creatureToCount = [tierValues](CCreature * creature) -> int
  230. {
  231. if(!creature->getAIValue() || tierValues.empty()) //bug #2681
  232. return 0; //this box won't be generated
  233. //Follow the rules from https://heroes.thelazy.net/index.php/Pandora%27s_Box
  234. int actualTier = creature->getLevel() > tierValues.size() ?
  235. tierValues.size() - 1 :
  236. creature->getLevel() - 1;
  237. float creaturesAmount = std::floor((static_cast<float>(tierValues[actualTier])) / creature->getAIValue());
  238. if (creaturesAmount < 1)
  239. {
  240. return 0;
  241. }
  242. else if(creaturesAmount <= 5)
  243. {
  244. //No change
  245. }
  246. else if(creaturesAmount <= 12)
  247. {
  248. creaturesAmount = std::ceil(creaturesAmount / 2) * 2;
  249. }
  250. else if(creaturesAmount <= 50)
  251. {
  252. creaturesAmount = std::round(creaturesAmount / 5) * 5;
  253. }
  254. else
  255. {
  256. creaturesAmount = std::round(creaturesAmount / 10) * 10;
  257. }
  258. return static_cast<int>(creaturesAmount);
  259. };
  260. for(auto * creature : creatures)
  261. {
  262. int creaturesAmount = creatureToCount(creature);
  263. if(!creaturesAmount)
  264. continue;
  265. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  266. {
  267. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  268. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  269. Rewardable::VisitInfo reward;
  270. reward.reward.creatures.emplace_back(creature, creaturesAmount);
  271. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  272. obj->configuration.info.push_back(reward);
  273. return obj;
  274. };
  275. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  276. oi.value = static_cast<ui32>((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) / 3);
  277. oi.probability = 3;
  278. if(!oi.templates.empty())
  279. addObjectToRandomPool(oi);
  280. }
  281. //Pandora with 12 spells of certain level
  282. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  283. {
  284. oi.generateObject = [i, this]() -> CGObjectInstance *
  285. {
  286. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  287. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  288. std::vector <CSpell *> spells;
  289. for(auto spell : VLC->spellh->objects)
  290. {
  291. if(map.isAllowedSpell(spell->id) && spell->getLevel() == i)
  292. spells.push_back(spell);
  293. }
  294. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  295. Rewardable::VisitInfo reward;
  296. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  297. {
  298. reward.reward.spells.push_back(spells[j]->id);
  299. }
  300. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  301. obj->configuration.info.push_back(reward);
  302. return obj;
  303. };
  304. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  305. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  306. oi.probability = 2;
  307. if(!oi.templates.empty())
  308. addObjectToRandomPool(oi);
  309. }
  310. //Pandora with 15 spells of certain school
  311. for(int i = 0; i < 4; i++)
  312. {
  313. oi.generateObject = [i, this]() -> CGObjectInstance *
  314. {
  315. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  316. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  317. std::vector <CSpell *> spells;
  318. for(auto spell : VLC->spellh->objects)
  319. {
  320. if(map.isAllowedSpell(spell->id) && spell->school[SpellSchool(i)])
  321. spells.push_back(spell);
  322. }
  323. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  324. Rewardable::VisitInfo reward;
  325. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  326. {
  327. reward.reward.spells.push_back(spells[j]->id);
  328. }
  329. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  330. obj->configuration.info.push_back(reward);
  331. return obj;
  332. };
  333. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  334. oi.value = generator.getConfig().pandoraSpellSchool;
  335. oi.probability = 2;
  336. if(!oi.templates.empty())
  337. addObjectToRandomPool(oi);
  338. }
  339. // Pandora box with 60 random spells
  340. oi.generateObject = [this]() -> CGObjectInstance *
  341. {
  342. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  343. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  344. std::vector <CSpell *> spells;
  345. for(auto spell : VLC->spellh->objects)
  346. {
  347. if(map.isAllowedSpell(spell->id))
  348. spells.push_back(spell);
  349. }
  350. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  351. Rewardable::VisitInfo reward;
  352. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  353. {
  354. reward.reward.spells.push_back(spells[j]->id);
  355. }
  356. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  357. obj->configuration.info.push_back(reward);
  358. return obj;
  359. };
  360. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  361. oi.value = generator.getConfig().pandoraSpell60;
  362. oi.probability = 2;
  363. if(!oi.templates.empty())
  364. addObjectToRandomPool(oi);
  365. //Seer huts with creatures or generic rewards
  366. if(zone.getConnectedZoneIds().size()) //Unlikely, but...
  367. {
  368. auto * qap = zone.getModificator<QuestArtifactPlacer>();
  369. if(!qap)
  370. {
  371. return; //TODO: throw?
  372. }
  373. const int questArtsRemaining = qap->getMaxQuestArtifactCount();
  374. if (!questArtsRemaining)
  375. {
  376. return;
  377. }
  378. //Generate Seer Hut one by one. Duplicated oi possible and should work fine.
  379. oi.maxPerZone = 1;
  380. std::vector<ObjectInfo> possibleSeerHuts;
  381. //14 creatures per town + 4 for each of gold / exp reward
  382. possibleSeerHuts.reserve(14 + 4 + 4);
  383. RandomGeneratorUtil::randomShuffle(creatures, zone.getRand());
  384. for(int i = 0; i < static_cast<int>(creatures.size()); i++)
  385. {
  386. auto * creature = creatures[i];
  387. int creaturesAmount = creatureToCount(creature);
  388. if(!creaturesAmount)
  389. continue;
  390. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  391. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, qap]() -> CGObjectInstance *
  392. {
  393. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  394. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  395. Rewardable::VisitInfo reward;
  396. reward.reward.creatures.emplace_back(creature->getId(), creaturesAmount);
  397. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  398. obj->configuration.info.push_back(reward);
  399. obj->quest->missionType = CQuest::MISSION_ART;
  400. ArtifactID artid = qap->drawRandomArtifact();
  401. obj->quest->addArtifactID(artid);
  402. obj->quest->lastDay = -1;
  403. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  404. generator.banQuestArt(artid);
  405. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  406. return obj;
  407. };
  408. oi.probability = 3;
  409. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  410. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) - 4000) / 3);
  411. if (oi.value > zone.getMaxTreasureValue())
  412. {
  413. continue;
  414. }
  415. else
  416. {
  417. if(!oi.templates.empty())
  418. possibleSeerHuts.push_back(oi);
  419. }
  420. }
  421. static int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  422. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  423. {
  424. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  425. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  426. oi.value = generator.getConfig().questValues[i];
  427. if (oi.value > zone.getMaxTreasureValue())
  428. {
  429. //Both variants have same value
  430. continue;
  431. }
  432. oi.probability = 10;
  433. oi.maxPerZone = 1;
  434. oi.generateObject = [i, randomAppearance, this, qap]() -> CGObjectInstance *
  435. {
  436. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  437. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  438. Rewardable::VisitInfo reward;
  439. reward.reward.heroExperience = generator.getConfig().questRewardValues[i];
  440. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  441. obj->configuration.info.push_back(reward);
  442. obj->quest->missionType = CQuest::MISSION_ART;
  443. ArtifactID artid = qap->drawRandomArtifact();
  444. obj->quest->addArtifactID(artid);
  445. obj->quest->lastDay = -1;
  446. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  447. generator.banQuestArt(artid);
  448. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  449. return obj;
  450. };
  451. if(!oi.templates.empty())
  452. possibleSeerHuts.push_back(oi);
  453. oi.generateObject = [i, randomAppearance, this, qap]() -> CGObjectInstance *
  454. {
  455. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  456. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  457. Rewardable::VisitInfo reward;
  458. reward.reward.resources[EGameResID::GOLD] = generator.getConfig().questRewardValues[i];
  459. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  460. obj->configuration.info.push_back(reward);
  461. obj->quest->missionType = CQuest::MISSION_ART;
  462. ArtifactID artid = qap->drawRandomArtifact();
  463. obj->quest->addArtifactID(artid);
  464. obj->quest->lastDay = -1;
  465. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  466. generator.banQuestArt(artid);
  467. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  468. return obj;
  469. };
  470. if(!oi.templates.empty())
  471. possibleSeerHuts.push_back(oi);
  472. }
  473. if (possibleSeerHuts.empty())
  474. {
  475. return;
  476. }
  477. for (size_t i = 0; i < questArtsRemaining; i++)
  478. {
  479. addObjectToRandomPool(*RandomGeneratorUtil::nextItem(possibleSeerHuts, zone.getRand()));
  480. }
  481. }
  482. }
  483. size_t TreasurePlacer::getPossibleObjectsSize() const
  484. {
  485. RecursiveLock lock(externalAccessMutex);
  486. return possibleObjects.size();
  487. }
  488. void TreasurePlacer::setMaxPrisons(size_t count)
  489. {
  490. RecursiveLock lock(externalAccessMutex);
  491. maxPrisons = count;
  492. }
  493. size_t TreasurePlacer::getMaxPrisons() const
  494. {
  495. RecursiveLock lock(externalAccessMutex);
  496. return maxPrisons;
  497. }
  498. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  499. {// no guard in a zone with "monsters: none" and for small treasures; water zones cen get monster strength ZONE_NONE elsewhere if needed
  500. return zone.monsterStrength != EMonsterStrength::ZONE_NONE && value > minGuardedValue;
  501. }
  502. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  503. {
  504. std::vector<ObjectInfo*> objectInfos;
  505. int maxValue = treasureInfo.max;
  506. int minValue = treasureInfo.min;
  507. const ui32 desiredValue =zone.getRand().nextInt(minValue, maxValue);
  508. int currentValue = 0;
  509. bool hasLargeObject = false;
  510. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  511. {
  512. auto * oi = getRandomObject(desiredValue, currentValue, !hasLargeObject);
  513. if(!oi) //fail
  514. break;
  515. bool visitableFromTop = true;
  516. for(auto & t : oi->templates)
  517. if(!t->isVisitableFromTop())
  518. visitableFromTop = false;
  519. if(visitableFromTop)
  520. {
  521. objectInfos.push_back(oi);
  522. }
  523. else
  524. {
  525. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  526. hasLargeObject = true;
  527. }
  528. //remove from possible objects
  529. assert(oi->maxPerZone);
  530. oi->maxPerZone--;
  531. currentValue += oi->value;
  532. }
  533. return objectInfos;
  534. }
  535. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  536. {
  537. rmg::Object rmgObject;
  538. for(const auto & oi : treasureInfos)
  539. {
  540. auto blockedArea = rmgObject.getArea();
  541. auto accessibleArea = rmgObject.getAccessibleArea();
  542. if(rmgObject.instances().empty())
  543. accessibleArea.add(int3());
  544. auto * object = oi->generateObject();
  545. if(oi->templates.empty())
  546. continue;
  547. object->appearance = *RandomGeneratorUtil::nextItem(oi->templates, zone.getRand());
  548. auto & instance = rmgObject.addInstance(*object);
  549. do
  550. {
  551. if(accessibleArea.empty())
  552. {
  553. //fail - fallback
  554. rmgObject.clear();
  555. return rmgObject;
  556. }
  557. std::vector<int3> bestPositions;
  558. if(densePlacement)
  559. {
  560. int bestPositionsWeight = std::numeric_limits<int>::max();
  561. for(const auto & t : accessibleArea.getTilesVector())
  562. {
  563. instance.setPosition(t);
  564. int w = rmgObject.getAccessibleArea().getTilesVector().size();
  565. if(w < bestPositionsWeight)
  566. {
  567. bestPositions.clear();
  568. bestPositions.push_back(t);
  569. bestPositionsWeight = w;
  570. }
  571. else if(w == bestPositionsWeight)
  572. {
  573. bestPositions.push_back(t);
  574. }
  575. }
  576. }
  577. else
  578. {
  579. bestPositions = accessibleArea.getTilesVector();
  580. }
  581. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, zone.getRand());
  582. instance.setPosition(nextPos - rmgObject.getPosition());
  583. auto instanceAccessibleArea = instance.getAccessibleArea();
  584. if(instance.getBlockedArea().getTilesVector().size() == 1)
  585. {
  586. if(instance.object().appearance->isVisitableFromTop() && instance.object().ID != Obj::CORPSE)
  587. instanceAccessibleArea.add(instance.getVisitablePosition());
  588. }
  589. //first object is good
  590. if(rmgObject.instances().size() == 1)
  591. break;
  592. //condition for good position
  593. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  594. break;
  595. //fail - new position
  596. accessibleArea.erase(nextPos);
  597. } while(true);
  598. }
  599. return rmgObject;
  600. }
  601. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, bool allowLargeObjects)
  602. {
  603. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  604. ui32 total = 0;
  605. //calculate actual treasure value range based on remaining value
  606. ui32 maxVal = desiredValue - currentValue;
  607. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  608. for(ObjectInfo & oi : possibleObjects) //copy constructor turned out to be costly
  609. {
  610. if(oi.value > maxVal)
  611. break; //this assumes values are sorted in ascending order
  612. bool visitableFromTop = true;
  613. for(auto & t : oi.templates)
  614. if(!t->isVisitableFromTop())
  615. visitableFromTop = false;
  616. if(!visitableFromTop && !allowLargeObjects)
  617. continue;
  618. if(oi.value >= minValue && oi.maxPerZone > 0)
  619. {
  620. total += oi.probability;
  621. thresholds.emplace_back(total, &oi);
  622. }
  623. }
  624. if(thresholds.empty())
  625. {
  626. return nullptr;
  627. }
  628. else
  629. {
  630. int r = zone.getRand().nextInt(1, total);
  631. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  632. {
  633. return static_cast<int>(rhs.first) < lhs;
  634. };
  635. //binary search = fastest
  636. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  637. return it->second;
  638. }
  639. }
  640. void TreasurePlacer::createTreasures(ObjectManager& manager)
  641. {
  642. const int maxAttempts = 2;
  643. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  644. int monsterStrength = (zone.monsterStrength == EMonsterStrength::ZONE_NONE ? 0 : zone.monsterStrength + mapMonsterStrength - 1); //array index from 0 to 4; pick any correct value for ZONE_NONE, minGuardedValue won't be used in this case anyway
  645. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  646. minGuardedValue = minGuardedValues[monsterStrength];
  647. auto valueComparator = [](const CTreasureInfo& lhs, const CTreasureInfo& rhs) -> bool
  648. {
  649. return lhs.max > rhs.max;
  650. };
  651. auto restoreZoneLimits = [](const std::vector<ObjectInfo*>& treasurePile)
  652. {
  653. for (auto* oi : treasurePile)
  654. {
  655. oi->maxPerZone++;
  656. }
  657. };
  658. //place biggest treasures first at large distance, place smaller ones inbetween
  659. auto treasureInfo = zone.getTreasureInfo();
  660. boost::sort(treasureInfo, valueComparator);
  661. //sort treasures by ascending value so we can stop checking treasures with too high value
  662. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  663. {
  664. return oi1.value < oi2.value;
  665. });
  666. size_t size = 0;
  667. {
  668. Zone::Lock lock(zone.areaMutex);
  669. size = zone.getArea().getTiles().size();
  670. }
  671. int totalDensity = 0;
  672. for (auto t = treasureInfo.begin(); t != treasureInfo.end(); t++)
  673. {
  674. std::vector<rmg::Object> treasures;
  675. //discard objects with too high value to be ever placed
  676. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  677. {
  678. return oi.value > t->max;
  679. });
  680. totalDensity += t->density;
  681. size_t count = size * t->density / 500;
  682. //Assure space for lesser treasures, if there are any left
  683. if (t != (treasureInfo.end() - 1))
  684. {
  685. const int averageValue = (t->min + t->max) / 2;
  686. if (averageValue > 10000)
  687. {
  688. //Will surely be guarded => larger piles => less space inbetween
  689. vstd::amin(count, size * (10.f / 500) / (std::sqrt((float)averageValue / 10000)));
  690. }
  691. }
  692. //this is squared distance for optimization purposes
  693. const float minDistance = std::max<float>((125.f / totalDensity), 1.0f);
  694. size_t emergencyLoopFinish = 0;
  695. while(treasures.size() < count && emergencyLoopFinish < count)
  696. {
  697. auto treasurePileInfos = prepareTreasurePile(*t);
  698. if (treasurePileInfos.empty())
  699. {
  700. emergencyLoopFinish++; //Exit potentially infinite loop for bad settings
  701. continue;
  702. }
  703. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo* oi) {return v + oi->value; });
  704. for (ui32 attempt = 0; attempt <= 2; attempt++)
  705. {
  706. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  707. if (rmgObject.instances().empty()) //handle incorrect placement
  708. {
  709. restoreZoneLimits(treasurePileInfos);
  710. continue;
  711. }
  712. //guard treasure pile
  713. bool guarded = isGuardNeededForTreasure(value);
  714. if (guarded)
  715. guarded = manager.addGuard(rmgObject, value);
  716. treasures.push_back(rmgObject);
  717. break;
  718. }
  719. }
  720. for (auto& rmgObject : treasures)
  721. {
  722. const bool guarded = rmgObject.isGuarded();
  723. for (int attempt = 0; attempt <= maxAttempts;)
  724. {
  725. auto path = rmg::Path::invalid();
  726. Zone::Lock lock(zone.areaMutex); //We are going to subtract this area
  727. auto possibleArea = zone.areaPossible();
  728. if (guarded)
  729. {
  730. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3& tile)
  731. {
  732. auto ti = map.getTileInfo(tile);
  733. if (ti.getNearestObjectDistance() < minDistance)
  734. return -1.f;
  735. for (const auto& t : rmgObject.getArea().getTilesVector())
  736. {
  737. if (map.getTileInfo(t).getNearestObjectDistance() < minDistance)
  738. return -1.f;
  739. }
  740. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  741. auto areaToBlock = rmgObject.getAccessibleArea(true);
  742. areaToBlock.subtract(guardedArea);
  743. if (areaToBlock.overlap(zone.freePaths()) || areaToBlock.overlap(manager.getVisitableArea()))
  744. return -1.f;
  745. return ti.getNearestObjectDistance();
  746. }, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  747. }
  748. else
  749. {
  750. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  751. }
  752. if (path.valid())
  753. {
  754. //debug purposes
  755. treasureArea.unite(rmgObject.getArea());
  756. if (guarded)
  757. {
  758. guards.unite(rmgObject.instances().back()->getBlockedArea());
  759. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  760. auto areaToBlock = rmgObject.getAccessibleArea(true);
  761. areaToBlock.subtract(guardedArea);
  762. treasureBlockArea.unite(areaToBlock);
  763. }
  764. zone.connectPath(path);
  765. manager.placeObject(rmgObject, guarded, true);
  766. break;
  767. }
  768. else
  769. {
  770. ++attempt;
  771. }
  772. }
  773. }
  774. }
  775. }
  776. char TreasurePlacer::dump(const int3 & t)
  777. {
  778. if(guards.contains(t))
  779. return '!';
  780. if(treasureArea.contains(t))
  781. return '$';
  782. if(treasureBlockArea.contains(t))
  783. return '*';
  784. return Modificator::dump(t);
  785. }
  786. void ObjectInfo::setTemplates(si32 type, si32 subtype, TerrainId terrainType)
  787. {
  788. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  789. if(!templHandler)
  790. return;
  791. templates = templHandler->getTemplates(terrainType);
  792. }
  793. VCMI_LIB_NAMESPACE_END