TreasurePlacer.cpp 26 KB

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