TreasurePlacer.cpp 31 KB

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