TreasurePlacer.cpp 31 KB

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