TreasurePlacer.cpp 30 KB

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