TreasurePlacer.cpp 28 KB

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