TreasurePlacer.cpp 25 KB

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