TreasurePlacer.cpp 30 KB

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