TreasurePlacer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. 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]() -> 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. accessibleArea.add(int3());
  574. }
  575. auto * object = oi->generateObject();
  576. if(oi->templates.empty())
  577. {
  578. logGlobal->warn("Deleting randomized object with no templates: %s", object->getObjectName());
  579. oi->destroyObject(object);
  580. delete object;
  581. continue;
  582. }
  583. auto templates = object->getObjectHandler()->getMostSpecificTemplates(zone.getTerrainType());
  584. if (templates.empty())
  585. {
  586. 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())));
  587. }
  588. object->appearance = *RandomGeneratorUtil::nextItem(templates, zone.getRand());
  589. //Put object in accessible area next to entrable area (excluding blockvis tiles)
  590. if (!entrableArea.empty())
  591. {
  592. auto entrableBorder = entrableArea.getBorderOutside();
  593. accessibleArea.erase_if([&](const int3 & tile)
  594. {
  595. return !entrableBorder.count(tile);
  596. });
  597. }
  598. auto & instance = rmgObject.addInstance(*object);
  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. auto valueComparator = [](const CTreasureInfo& lhs, const CTreasureInfo& rhs) -> bool
  706. {
  707. return lhs.max > rhs.max;
  708. };
  709. auto restoreZoneLimits = [](const std::vector<ObjectInfo*>& treasurePile)
  710. {
  711. for (auto* oi : treasurePile)
  712. {
  713. oi->maxPerZone++;
  714. }
  715. };
  716. //place biggest treasures first at large distance, place smaller ones inbetween
  717. auto treasureInfo = zone.getTreasureInfo();
  718. boost::sort(treasureInfo, valueComparator);
  719. //sort treasures by ascending value so we can stop checking treasures with too high value
  720. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  721. {
  722. return oi1.value < oi2.value;
  723. });
  724. size_t size = 0;
  725. {
  726. Zone::Lock lock(zone.areaMutex);
  727. size = zone.getArea().getTilesVector().size();
  728. }
  729. int totalDensity = 0;
  730. for (auto t = treasureInfo.begin(); t != treasureInfo.end(); t++)
  731. {
  732. std::vector<rmg::Object> treasures;
  733. //discard objects with too high value to be ever placed
  734. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  735. {
  736. return oi.value > t->max;
  737. });
  738. totalDensity += t->density;
  739. const int DENSITY_CONSTANT = 300;
  740. size_t count = (size * t->density) / DENSITY_CONSTANT;
  741. //Assure space for lesser treasures, if there are any left
  742. const int averageValue = (t->min + t->max) / 2;
  743. if (t != (treasureInfo.end() - 1))
  744. {
  745. if (averageValue > 10000)
  746. {
  747. //Will surely be guarded => larger piles => less space inbetween
  748. vstd::amin(count, size * (10.f / DENSITY_CONSTANT) / (std::sqrt((float)averageValue / 10000)));
  749. }
  750. }
  751. //this is squared distance for optimization purposes
  752. const float minDistance = std::max<float>((125.f / totalDensity), 1.0f);
  753. size_t emergencyLoopFinish = 0;
  754. while(treasures.size() < count && emergencyLoopFinish < count)
  755. {
  756. auto treasurePileInfos = prepareTreasurePile(*t);
  757. if (treasurePileInfos.empty())
  758. {
  759. emergencyLoopFinish++; //Exit potentially infinite loop for bad settings
  760. continue;
  761. }
  762. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo* oi) {return v + oi->value; });
  763. const ui32 maxPileGenerationAttemps = 2;
  764. for (ui32 attempt = 0; attempt < maxPileGenerationAttemps; attempt++)
  765. {
  766. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  767. if (rmgObject.instances().empty())
  768. {
  769. // Restore once if all attemps failed
  770. if (attempt == (maxPileGenerationAttemps - 1))
  771. {
  772. restoreZoneLimits(treasurePileInfos);
  773. }
  774. continue;
  775. }
  776. //guard treasure pile
  777. bool guarded = isGuardNeededForTreasure(value);
  778. if (guarded)
  779. guarded = manager.addGuard(rmgObject, value);
  780. treasures.push_back(rmgObject);
  781. break;
  782. }
  783. }
  784. for (auto& rmgObject : treasures)
  785. {
  786. const bool guarded = rmgObject.isGuarded();
  787. auto path = rmg::Path::invalid();
  788. Zone::Lock lock(zone.areaMutex); //We are going to subtract this area
  789. auto possibleArea = zone.areaPossible();
  790. possibleArea.erase_if([this, &minDistance](const int3& tile) -> bool
  791. {
  792. auto ti = map.getTileInfo(tile);
  793. return (ti.getNearestObjectDistance() < minDistance);
  794. });
  795. if (guarded)
  796. {
  797. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3& tile)
  798. {
  799. float bestDistance = 10e9;
  800. for (const auto& t : rmgObject.getArea().getTilesVector())
  801. {
  802. float distance = map.getTileInfo(t).getNearestObjectDistance();
  803. if (distance < minDistance)
  804. return -1.f;
  805. else
  806. vstd::amin(bestDistance, distance);
  807. }
  808. const auto & guardedArea = rmgObject.instances().back()->getAccessibleArea();
  809. const auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  810. if (zone.freePaths().overlap(areaToBlock) || manager.getVisitableArea().overlap(areaToBlock))
  811. return -1.f;
  812. return bestDistance;
  813. }, guarded, false, ObjectManager::OptimizeType::BOTH);
  814. }
  815. else
  816. {
  817. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  818. }
  819. lock.unlock();
  820. if (path.valid())
  821. {
  822. //debug purposes
  823. treasureArea.unite(rmgObject.getArea());
  824. if (guarded)
  825. {
  826. guards.unite(rmgObject.instances().back()->getBlockedArea());
  827. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  828. auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  829. treasureBlockArea.unite(areaToBlock);
  830. }
  831. zone.connectPath(path);
  832. manager.placeObject(rmgObject, guarded, true);
  833. }
  834. }
  835. }
  836. }
  837. char TreasurePlacer::dump(const int3 & t)
  838. {
  839. if(guards.contains(t))
  840. return '!';
  841. if(treasureArea.contains(t))
  842. return '$';
  843. if(treasureBlockArea.contains(t))
  844. return '*';
  845. return Modificator::dump(t);
  846. }
  847. void ObjectInfo::setTemplates(MapObjectID type, MapObjectSubID subtype, TerrainId terrainType)
  848. {
  849. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  850. if(!templHandler)
  851. return;
  852. templates = templHandler->getTemplates(terrainType);
  853. }
  854. VCMI_LIB_NAMESPACE_END