TreasurePlacer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. if (!questArtsRemaining)
  357. {
  358. return;
  359. }
  360. //Generate Seer Hut one by one. Duplicated oi possible and should work fine.
  361. oi.maxPerZone = 1;
  362. std::vector<ObjectInfo> possibleSeerHuts;
  363. //14 creatures per town + 4 for each of gold / exp reward
  364. possibleSeerHuts.reserve(14 + 4 + 4);
  365. RandomGeneratorUtil::randomShuffle(creatures, zone.getRand());
  366. for(int i = 0; i < static_cast<int>(creatures.size()); i++)
  367. {
  368. auto * creature = creatures[i];
  369. int creaturesAmount = creatureToCount(creature);
  370. if(!creaturesAmount)
  371. continue;
  372. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  373. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, qap]() -> CGObjectInstance *
  374. {
  375. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  376. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  377. obj->rewardType = CGSeerHut::CREATURE;
  378. obj->rID = creature->getId();
  379. obj->rVal = creaturesAmount;
  380. obj->quest->missionType = CQuest::MISSION_ART;
  381. ArtifactID artid = qap->drawRandomArtifact();
  382. obj->quest->addArtifactID(artid);
  383. obj->quest->lastDay = -1;
  384. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  385. generator.banQuestArt(artid);
  386. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  387. return obj;
  388. };
  389. oi.probability = 3;
  390. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  391. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) - 4000) / 3);
  392. if (oi.value > zone.getMaxTreasureValue())
  393. {
  394. continue;
  395. }
  396. else
  397. {
  398. possibleSeerHuts.push_back(oi);
  399. }
  400. }
  401. static int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  402. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  403. {
  404. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  405. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  406. oi.value = generator.getConfig().questValues[i];
  407. if (oi.value > zone.getMaxTreasureValue())
  408. {
  409. //Both variants have same value
  410. continue;
  411. }
  412. oi.probability = 10;
  413. oi.generateObject = [i, randomAppearance, this, qap]() -> CGObjectInstance *
  414. {
  415. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  416. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  417. obj->rewardType = CGSeerHut::EXPERIENCE;
  418. obj->rID = 0; //unitialized?
  419. obj->rVal = generator.getConfig().questRewardValues[i];
  420. obj->quest->missionType = CQuest::MISSION_ART;
  421. ArtifactID artid = qap->drawRandomArtifact();
  422. obj->quest->addArtifactID(artid);
  423. obj->quest->lastDay = -1;
  424. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  425. generator.banQuestArt(artid);
  426. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  427. return obj;
  428. };
  429. possibleSeerHuts.push_back(oi);
  430. oi.generateObject = [i, randomAppearance, this, qap]() -> CGObjectInstance *
  431. {
  432. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  433. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  434. obj->rewardType = CGSeerHut::RESOURCES;
  435. obj->rID = GameResID(EGameResID::GOLD);
  436. obj->rVal = generator.getConfig().questRewardValues[i];
  437. obj->quest->missionType = CQuest::MISSION_ART;
  438. ArtifactID artid = qap->drawRandomArtifact();
  439. obj->quest->addArtifactID(artid);
  440. obj->quest->lastDay = -1;
  441. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  442. generator.banQuestArt(artid);
  443. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  444. return obj;
  445. };
  446. possibleSeerHuts.push_back(oi);
  447. }
  448. if (possibleSeerHuts.empty())
  449. {
  450. return;
  451. }
  452. for (size_t i = 0; i < questArtsRemaining; i++)
  453. {
  454. addObjectToRandomPool(*RandomGeneratorUtil::nextItem(possibleSeerHuts, zone.getRand()));
  455. }
  456. }
  457. }
  458. size_t TreasurePlacer::getPossibleObjectsSize() const
  459. {
  460. RecursiveLock lock(externalAccessMutex);
  461. return possibleObjects.size();
  462. }
  463. void TreasurePlacer::setMaxPrisons(size_t count)
  464. {
  465. RecursiveLock lock(externalAccessMutex);
  466. maxPrisons = count;
  467. }
  468. size_t TreasurePlacer::getMaxPrisons() const
  469. {
  470. RecursiveLock lock(externalAccessMutex);
  471. return maxPrisons;
  472. }
  473. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  474. {// no guard in a zone with "monsters: none" and for small treasures; water zones cen get monster strength ZONE_NONE elsewhere if needed
  475. return zone.monsterStrength != EMonsterStrength::ZONE_NONE && value > minGuardedValue;
  476. }
  477. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  478. {
  479. std::vector<ObjectInfo*> objectInfos;
  480. int maxValue = treasureInfo.max;
  481. int minValue = treasureInfo.min;
  482. const ui32 desiredValue =zone.getRand().nextInt(minValue, maxValue);
  483. int currentValue = 0;
  484. bool hasLargeObject = false;
  485. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  486. {
  487. auto * oi = getRandomObject(desiredValue, currentValue, !hasLargeObject);
  488. if(!oi) //fail
  489. break;
  490. if(oi->templ->isVisitableFromTop())
  491. {
  492. objectInfos.push_back(oi);
  493. }
  494. else
  495. {
  496. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  497. hasLargeObject = true;
  498. }
  499. //remove from possible objects
  500. assert(oi->maxPerZone);
  501. oi->maxPerZone--;
  502. currentValue += oi->value;
  503. }
  504. return objectInfos;
  505. }
  506. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  507. {
  508. rmg::Object rmgObject;
  509. for(const auto & oi : treasureInfos)
  510. {
  511. auto blockedArea = rmgObject.getArea();
  512. auto accessibleArea = rmgObject.getAccessibleArea();
  513. if(rmgObject.instances().empty())
  514. accessibleArea.add(int3());
  515. auto * object = oi->generateObject();
  516. object->appearance = oi->templ;
  517. auto & instance = rmgObject.addInstance(*object);
  518. do
  519. {
  520. if(accessibleArea.empty())
  521. {
  522. //fail - fallback
  523. rmgObject.clear();
  524. return rmgObject;
  525. }
  526. std::vector<int3> bestPositions;
  527. if(densePlacement)
  528. {
  529. int bestPositionsWeight = std::numeric_limits<int>::max();
  530. for(const auto & t : accessibleArea.getTilesVector())
  531. {
  532. instance.setPosition(t);
  533. int w = rmgObject.getAccessibleArea().getTilesVector().size();
  534. if(w < bestPositionsWeight)
  535. {
  536. bestPositions.clear();
  537. bestPositions.push_back(t);
  538. bestPositionsWeight = w;
  539. }
  540. else if(w == bestPositionsWeight)
  541. {
  542. bestPositions.push_back(t);
  543. }
  544. }
  545. }
  546. else
  547. {
  548. bestPositions = accessibleArea.getTilesVector();
  549. }
  550. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, zone.getRand());
  551. instance.setPosition(nextPos - rmgObject.getPosition());
  552. auto instanceAccessibleArea = instance.getAccessibleArea();
  553. if(instance.getBlockedArea().getTilesVector().size() == 1)
  554. {
  555. if(instance.object().appearance->isVisitableFromTop() && instance.object().ID != Obj::CORPSE)
  556. instanceAccessibleArea.add(instance.getVisitablePosition());
  557. }
  558. //first object is good
  559. if(rmgObject.instances().size() == 1)
  560. break;
  561. //condition for good position
  562. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  563. break;
  564. //fail - new position
  565. accessibleArea.erase(nextPos);
  566. } while(true);
  567. }
  568. return rmgObject;
  569. }
  570. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, bool allowLargeObjects)
  571. {
  572. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  573. ui32 total = 0;
  574. //calculate actual treasure value range based on remaining value
  575. ui32 maxVal = desiredValue - currentValue;
  576. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  577. for(ObjectInfo & oi : possibleObjects) //copy constructor turned out to be costly
  578. {
  579. if(oi.value > maxVal)
  580. break; //this assumes values are sorted in ascending order
  581. if(!oi.templ->isVisitableFromTop() && !allowLargeObjects)
  582. continue;
  583. if(oi.value >= minValue && oi.maxPerZone > 0)
  584. {
  585. total += oi.probability;
  586. thresholds.emplace_back(total, &oi);
  587. }
  588. }
  589. if(thresholds.empty())
  590. {
  591. return nullptr;
  592. }
  593. else
  594. {
  595. int r = zone.getRand().nextInt(1, total);
  596. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  597. {
  598. return static_cast<int>(rhs.first) < lhs;
  599. };
  600. //binary search = fastest
  601. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  602. return it->second;
  603. }
  604. }
  605. void TreasurePlacer::createTreasures(ObjectManager& manager)
  606. {
  607. const int maxAttempts = 2;
  608. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  609. 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
  610. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  611. minGuardedValue = minGuardedValues[monsterStrength];
  612. auto valueComparator = [](const CTreasureInfo& lhs, const CTreasureInfo& rhs) -> bool
  613. {
  614. return lhs.max > rhs.max;
  615. };
  616. auto restoreZoneLimits = [](const std::vector<ObjectInfo*>& treasurePile)
  617. {
  618. for (auto* oi : treasurePile)
  619. {
  620. oi->maxPerZone++;
  621. }
  622. };
  623. //place biggest treasures first at large distance, place smaller ones inbetween
  624. auto treasureInfo = zone.getTreasureInfo();
  625. boost::sort(treasureInfo, valueComparator);
  626. //sort treasures by ascending value so we can stop checking treasures with too high value
  627. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  628. {
  629. return oi1.value < oi2.value;
  630. });
  631. size_t size = 0;
  632. {
  633. Zone::Lock lock(zone.areaMutex);
  634. size = zone.getArea().getTiles().size();
  635. }
  636. int totalDensity = 0;
  637. for (auto t = treasureInfo.begin(); t != treasureInfo.end(); t++)
  638. {
  639. std::vector<rmg::Object> treasures;
  640. //discard objects with too high value to be ever placed
  641. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  642. {
  643. return oi.value > t->max;
  644. });
  645. totalDensity += t->density;
  646. size_t count = size * t->density / 500;
  647. //Assure space for lesser treasures, if there are any left
  648. if (t != (treasureInfo.end() - 1))
  649. {
  650. const int averageValue = (t->min + t->max) / 2;
  651. if (averageValue > 10000)
  652. {
  653. //Will surely be guarded => larger piles => less space inbetween
  654. vstd::amin(count, size * (10.f / 500) / (std::sqrt((float)averageValue / 10000)));
  655. }
  656. }
  657. //this is squared distance for optimization purposes
  658. const float minDistance = std::max<float>((125.f / totalDensity), 1.0f);
  659. size_t emergencyLoopFinish = 0;
  660. while(treasures.size() < count && emergencyLoopFinish < count)
  661. {
  662. auto treasurePileInfos = prepareTreasurePile(*t);
  663. if (treasurePileInfos.empty())
  664. {
  665. emergencyLoopFinish++; //Exit potentially infinite loop for bad settings
  666. continue;
  667. }
  668. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo* oi) {return v + oi->value; });
  669. for (ui32 attempt = 0; attempt <= 2; attempt++)
  670. {
  671. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  672. if (rmgObject.instances().empty()) //handle incorrect placement
  673. {
  674. restoreZoneLimits(treasurePileInfos);
  675. continue;
  676. }
  677. //guard treasure pile
  678. bool guarded = isGuardNeededForTreasure(value);
  679. if (guarded)
  680. guarded = manager.addGuard(rmgObject, value);
  681. treasures.push_back(rmgObject);
  682. break;
  683. }
  684. }
  685. for (auto& rmgObject : treasures)
  686. {
  687. const bool guarded = rmgObject.isGuarded();
  688. for (int attempt = 0; attempt <= maxAttempts;)
  689. {
  690. auto path = rmg::Path::invalid();
  691. Zone::Lock lock(zone.areaMutex); //We are going to subtract this area
  692. auto possibleArea = zone.areaPossible();
  693. if (guarded)
  694. {
  695. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3& tile)
  696. {
  697. auto ti = map.getTileInfo(tile);
  698. if (ti.getNearestObjectDistance() < minDistance)
  699. return -1.f;
  700. for (const auto& t : rmgObject.getArea().getTilesVector())
  701. {
  702. if (map.getTileInfo(t).getNearestObjectDistance() < minDistance)
  703. return -1.f;
  704. }
  705. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  706. auto areaToBlock = rmgObject.getAccessibleArea(true);
  707. areaToBlock.subtract(guardedArea);
  708. if (areaToBlock.overlap(zone.freePaths()) || areaToBlock.overlap(manager.getVisitableArea()))
  709. return -1.f;
  710. return ti.getNearestObjectDistance();
  711. }, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  712. }
  713. else
  714. {
  715. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  716. }
  717. if (path.valid())
  718. {
  719. //debug purposes
  720. treasureArea.unite(rmgObject.getArea());
  721. if (guarded)
  722. {
  723. guards.unite(rmgObject.instances().back()->getBlockedArea());
  724. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  725. auto areaToBlock = rmgObject.getAccessibleArea(true);
  726. areaToBlock.subtract(guardedArea);
  727. treasureBlockArea.unite(areaToBlock);
  728. }
  729. zone.connectPath(path);
  730. manager.placeObject(rmgObject, guarded, true);
  731. break;
  732. }
  733. else
  734. {
  735. ++attempt;
  736. }
  737. }
  738. }
  739. }
  740. }
  741. char TreasurePlacer::dump(const int3 & t)
  742. {
  743. if(guards.contains(t))
  744. return '!';
  745. if(treasureArea.contains(t))
  746. return '$';
  747. if(treasureBlockArea.contains(t))
  748. return '*';
  749. return Modificator::dump(t);
  750. }
  751. void ObjectInfo::setTemplate(si32 type, si32 subtype, TerrainId terrainType)
  752. {
  753. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  754. if(!templHandler)
  755. return;
  756. auto templates = templHandler->getTemplates(terrainType);
  757. if(templates.empty())
  758. return;
  759. templ = templates.front();
  760. }
  761. VCMI_LIB_NAMESPACE_END