TreasurePlacer.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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 "../CRmgTemplate.h"
  13. #include "../CMapGenerator.h"
  14. #include "../Functions.h"
  15. #include "ObjectManager.h"
  16. #include "RoadPlacer.h"
  17. #include "ConnectionsPlacer.h"
  18. #include "../RmgMap.h"
  19. #include "../TileInfo.h"
  20. #include "../CZonePlacer.h"
  21. #include "PrisonHeroPlacer.h"
  22. #include "QuestArtifactPlacer.h"
  23. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  24. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  25. #include "../../mapObjectConstructors/DwellingInstanceConstructor.h"
  26. #include "../../rewardable/Info.h"
  27. #include "../../mapObjects/CGHeroInstance.h"
  28. #include "../../mapObjects/CGPandoraBox.h"
  29. #include "../../mapObjects/CQuest.h"
  30. #include "../../mapObjects/MiscObjects.h"
  31. #include "../../CCreatureHandler.h"
  32. #include "../../spells/CSpellHandler.h" //for choosing random spells
  33. #include "../../mapping/CMap.h"
  34. #include "../../mapping/CMapEditManager.h"
  35. #include <vstd/RNG.h>
  36. VCMI_LIB_NAMESPACE_BEGIN
  37. void TreasurePlacer::process()
  38. {
  39. if (zone.getMaxTreasureValue() == 0)
  40. {
  41. //No treasures at all
  42. return;
  43. }
  44. tierValues = generator.getConfig().pandoraCreatureValues;
  45. // Add all native creatures
  46. for(auto const & cre : LIBRARY->creh->objects)
  47. {
  48. if(!cre->special && cre->getFactionID() == zone.getTownType())
  49. {
  50. creatures.push_back(cre.get());
  51. }
  52. }
  53. // Get default objects
  54. addAllPossibleObjects();
  55. // Override with custom objects
  56. objects.patchWithZoneConfig(zone, this);
  57. auto * m = zone.getModificator<ObjectManager>();
  58. if(m)
  59. createTreasures(*m);
  60. }
  61. void TreasurePlacer::init()
  62. {
  63. maxPrisons = 0; //Should be in the constructor, but we use macro for that
  64. DEPENDENCY(ObjectManager);
  65. DEPENDENCY(ConnectionsPlacer);
  66. DEPENDENCY_ALL(PrisonHeroPlacer);
  67. DEPENDENCY(RoadPlacer);
  68. }
  69. void TreasurePlacer::addObjectToRandomPool(const ObjectInfo& oi)
  70. {
  71. if (oi.templates.empty())
  72. {
  73. logGlobal->error("Attempt to add ObjectInfo with no templates! Value: %d", oi.value);
  74. return;
  75. }
  76. if (!oi.generateObject)
  77. {
  78. logGlobal->error("Attempt to add ObjectInfo with no generateObject function! Value: %d", oi.value);
  79. return;
  80. }
  81. if (!oi.maxPerZone)
  82. {
  83. logGlobal->warn("Attempt to add ObjectInfo with 0 maxPerZone! Value: %d", oi.value);
  84. return;
  85. }
  86. RecursiveLock lock(externalAccessMutex);
  87. objects.addObject(oi);
  88. }
  89. void TreasurePlacer::addAllPossibleObjects()
  90. {
  91. addCommonObjects();
  92. addDwellings();
  93. addPandoraBoxes();
  94. addSeerHuts();
  95. addPrisons();
  96. addScrolls();
  97. }
  98. void TreasurePlacer::addCommonObjects()
  99. {
  100. for(auto primaryID : LIBRARY->objtypeh->knownObjects())
  101. {
  102. for(auto secondaryID : LIBRARY->objtypeh->knownSubObjects(primaryID))
  103. {
  104. auto handler = LIBRARY->objtypeh->getHandlerFor(primaryID, secondaryID);
  105. if(!handler->isStaticObject() && handler->getRMGInfo().value)
  106. {
  107. auto rmgInfo = handler->getRMGInfo();
  108. if (rmgInfo.mapLimit || rmgInfo.value > zone.getMaxTreasureValue())
  109. {
  110. //Skip objects with per-map limit here
  111. continue;
  112. }
  113. ObjectInfo oi(primaryID, secondaryID);
  114. setBasicProperties(oi, CompoundMapObjectID(primaryID, secondaryID));
  115. oi.value = rmgInfo.value;
  116. oi.probability = rmgInfo.rarity;
  117. oi.maxPerZone = rmgInfo.zoneLimit;
  118. if(!oi.templates.empty())
  119. addObjectToRandomPool(oi);
  120. }
  121. }
  122. }
  123. }
  124. void TreasurePlacer::setBasicProperties(ObjectInfo & oi, CompoundMapObjectID objid) const
  125. {
  126. oi.generateObject = [this, objid]() -> std::shared_ptr<CGObjectInstance>
  127. {
  128. return LIBRARY->objtypeh->getHandlerFor(objid)->create(map.mapInstance->cb, nullptr);
  129. };
  130. oi.setTemplates(objid.primaryID, objid.secondaryID, zone.getTerrainType());
  131. }
  132. void TreasurePlacer::addPrisons()
  133. {
  134. //Generate Prison on water only if it has a template
  135. auto prisonTemplates = LIBRARY->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(zone.getTerrainType());
  136. if (!prisonTemplates.empty())
  137. {
  138. PrisonHeroPlacer * prisonHeroPlacer = nullptr;
  139. for(auto & z : map.getZones())
  140. {
  141. prisonHeroPlacer = z.second->getModificator<PrisonHeroPlacer>();
  142. if (prisonHeroPlacer)
  143. {
  144. break;
  145. }
  146. }
  147. //prisons
  148. //levels 1, 5, 10, 20, 30
  149. static const int prisonsLevels = std::min(generator.getConfig().prisonExperience.size(), generator.getConfig().prisonValues.size());
  150. size_t prisonsLeft = getMaxPrisons();
  151. for (int i = prisonsLevels - 1; i >= 0; i--)
  152. {
  153. ObjectInfo oi(Obj::PRISON, 0); // Create new instance which will hold destructor operation
  154. oi.value = generator.getConfig().prisonValues[i];
  155. if (oi.value > zone.getMaxTreasureValue())
  156. {
  157. continue;
  158. }
  159. oi.generateObject = [i, this, prisonHeroPlacer]() -> std::shared_ptr<CGObjectInstance>
  160. {
  161. HeroTypeID hid = prisonHeroPlacer->drawRandomHero();
  162. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PRISON, 0);
  163. auto obj = std::dynamic_pointer_cast<CGHeroInstance>(factory->create(map.mapInstance->cb, nullptr));
  164. obj->setHeroType(hid); //will be initialized later
  165. obj->exp = generator.getConfig().prisonExperience[i];
  166. obj->setOwner(PlayerColor::NEUTRAL);
  167. return obj;
  168. };
  169. oi.destroyObject = [prisonHeroPlacer](CGObjectInstance& obj)
  170. {
  171. // Hero can be used again
  172. auto & hero = dynamic_cast<CGHeroInstance&>(obj);
  173. prisonHeroPlacer->restoreDrawnHero(hero.getHeroTypeID());
  174. };
  175. oi.setTemplates(Obj::PRISON, 0, zone.getTerrainType());
  176. oi.value = generator.getConfig().prisonValues[i];
  177. oi.probability = 30;
  178. //Distribute all allowed prisons, starting from the most valuable
  179. oi.maxPerZone = (std::ceil((float)prisonsLeft / (i + 1)));
  180. prisonsLeft -= oi.maxPerZone;
  181. if(!oi.templates.empty())
  182. addObjectToRandomPool(oi);
  183. }
  184. }
  185. }
  186. void TreasurePlacer::addDwellings()
  187. {
  188. if(zone.getType() == ETemplateZoneType::WATER)
  189. return;
  190. //dwellings
  191. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  192. for(auto dwellingType : dwellingTypes)
  193. {
  194. auto subObjects = LIBRARY->objtypeh->knownSubObjects(dwellingType);
  195. if(dwellingType == Obj::CREATURE_GENERATOR1)
  196. {
  197. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  198. static const MapObjectSubID elementalConfluxROE[] = {7, 13, 16, 47};
  199. for(auto const & i : elementalConfluxROE)
  200. vstd::erase_if_present(subObjects, i);
  201. }
  202. for(auto secondaryID : subObjects)
  203. {
  204. const auto * dwellingHandler = dynamic_cast<const DwellingInstanceConstructor *>(LIBRARY->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  205. auto creatures = dwellingHandler->getProducedCreatures();
  206. if(creatures.empty())
  207. continue;
  208. const auto * cre = creatures.front();
  209. if(cre->getFactionID() == zone.getTownType())
  210. {
  211. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->getFactionID()));
  212. ObjectInfo oi(dwellingType, secondaryID);
  213. setBasicProperties(oi, CompoundMapObjectID(dwellingType, secondaryID));
  214. oi.value = static_cast<ui32>(cre->getAIValue() * cre->getGrowth() * (1 + (nativeZonesCount / map.getTotalZoneCount()) + (nativeZonesCount / 2)));
  215. oi.probability = 40;
  216. oi.generateObject = [this, secondaryID, dwellingType]() -> std::shared_ptr<CGObjectInstance>
  217. {
  218. auto obj = LIBRARY->objtypeh->getHandlerFor(dwellingType, secondaryID)->create(map.mapInstance->cb, nullptr);
  219. obj->tempOwner = PlayerColor::NEUTRAL;
  220. return obj;
  221. };
  222. if(!oi.templates.empty())
  223. addObjectToRandomPool(oi);
  224. }
  225. }
  226. }
  227. }
  228. void TreasurePlacer::addScrolls()
  229. {
  230. if(zone.getType() == ETemplateZoneType::WATER)
  231. return;
  232. ObjectInfo oi(Obj::SPELL_SCROLL, 0);
  233. for(int i = 0; i < generator.getConfig().scrollValues.size(); i++)
  234. {
  235. oi.generateObject = [i, this]() -> std::shared_ptr<CGObjectInstance>
  236. {
  237. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  238. auto obj = std::dynamic_pointer_cast<CGArtifact>(factory->create(map.mapInstance->cb, nullptr));
  239. std::vector<SpellID> out;
  240. for(auto spellID : LIBRARY->spellh->getDefaultAllowed())
  241. {
  242. if(map.isAllowedSpell(spellID) && spellID.toSpell()->getLevel() == i + 1)
  243. out.push_back(spellID);
  244. }
  245. auto * a = map.mapInstance->createScroll(*RandomGeneratorUtil::nextItem(out, zone.getRand()));
  246. obj->setArtifactInstance(a);
  247. return obj;
  248. };
  249. oi.setTemplates(Obj::SPELL_SCROLL, 0, zone.getTerrainType());
  250. oi.value = generator.getConfig().scrollValues[i];
  251. oi.probability = 30;
  252. if(!oi.templates.empty())
  253. addObjectToRandomPool(oi);
  254. }
  255. }
  256. void TreasurePlacer::addPandoraBoxes()
  257. {
  258. if(zone.getType() == ETemplateZoneType::WATER)
  259. return;
  260. addPandoraBoxesWithGold();
  261. addPandoraBoxesWithExperience();
  262. addPandoraBoxesWithCreatures();
  263. addPandoraBoxesWithSpells();
  264. }
  265. void TreasurePlacer::addPandoraBoxesWithGold()
  266. {
  267. ObjectInfo oi(Obj::PANDORAS_BOX, 0);
  268. for(int i = 1; i < 5; i++)
  269. {
  270. oi.generateObject = [this, i]() -> std::shared_ptr<CGObjectInstance>
  271. {
  272. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  273. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  274. Rewardable::VisitInfo reward;
  275. reward.reward.resources[EGameResID::GOLD] = i * 5000;
  276. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  277. obj->configuration.info.push_back(reward);
  278. return obj;
  279. };
  280. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  281. oi.value = i * generator.getConfig().pandoraMultiplierGold;
  282. oi.probability = 5;
  283. if(!oi.templates.empty())
  284. addObjectToRandomPool(oi);
  285. }
  286. }
  287. void TreasurePlacer::addPandoraBoxesWithExperience()
  288. {
  289. ObjectInfo oi(Obj::PANDORAS_BOX, 0);
  290. for(int i = 1; i < 5; i++)
  291. {
  292. oi.generateObject = [this, i]() -> std::shared_ptr<CGObjectInstance>
  293. {
  294. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  295. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  296. Rewardable::VisitInfo reward;
  297. reward.reward.heroExperience = i * 5000;
  298. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  299. obj->configuration.info.push_back(reward);
  300. return obj;
  301. };
  302. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  303. oi.value = i * generator.getConfig().pandoraMultiplierExperience;
  304. oi.probability = 20;
  305. if(!oi.templates.empty())
  306. addObjectToRandomPool(oi);
  307. }
  308. }
  309. void TreasurePlacer::addPandoraBoxesWithCreatures()
  310. {
  311. for(auto * creature : creatures)
  312. {
  313. int creaturesAmount = creatureToCount(creature);
  314. if(!creaturesAmount)
  315. continue;
  316. ObjectInfo oi(Obj::PANDORAS_BOX, 0);
  317. oi.generateObject = [this, creature, creaturesAmount]() -> std::shared_ptr<CGObjectInstance>
  318. {
  319. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  320. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  321. Rewardable::VisitInfo reward;
  322. reward.reward.creatures.emplace_back(creature, creaturesAmount);
  323. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  324. obj->configuration.info.push_back(reward);
  325. return obj;
  326. };
  327. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  328. oi.value = static_cast<ui32>(creature->getAIValue() * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFactionID())) / map.getTotalZoneCount()));
  329. oi.probability = 3;
  330. if(!oi.templates.empty())
  331. addObjectToRandomPool(oi);
  332. }
  333. }
  334. void TreasurePlacer::addPandoraBoxesWithSpells()
  335. {
  336. ObjectInfo oi(Obj::PANDORAS_BOX, 0);
  337. //Pandora with 12 spells of certain level
  338. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  339. {
  340. oi.generateObject = [i, this]() -> std::shared_ptr<CGObjectInstance>
  341. {
  342. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  343. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  344. std::vector <const CSpell *> spells;
  345. for(auto spellID : LIBRARY->spellh->getDefaultAllowed())
  346. {
  347. if(map.isAllowedSpell(spellID) && spellID.toSpell()->getLevel() == i)
  348. spells.push_back(spellID.toSpell());
  349. }
  350. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  351. Rewardable::VisitInfo reward;
  352. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  353. {
  354. reward.reward.spells.push_back(spells[j]->id);
  355. }
  356. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  357. obj->configuration.info.push_back(reward);
  358. return obj;
  359. };
  360. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  361. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  362. oi.probability = 2;
  363. if(!oi.templates.empty())
  364. addObjectToRandomPool(oi);
  365. }
  366. //Pandora with 15 spells of certain school
  367. for(int i = 0; i < 4; i++)
  368. {
  369. oi.generateObject = [i, this]() -> std::shared_ptr<CGObjectInstance>
  370. {
  371. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  372. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  373. std::vector <const CSpell *> spells;
  374. for(auto spellID : LIBRARY->spellh->getDefaultAllowed())
  375. {
  376. if(map.isAllowedSpell(spellID) && spellID.toSpell()->hasSchool(SpellSchool(i)))
  377. spells.push_back(spellID.toSpell());
  378. }
  379. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  380. Rewardable::VisitInfo reward;
  381. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  382. {
  383. reward.reward.spells.push_back(spells[j]->id);
  384. }
  385. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  386. obj->configuration.info.push_back(reward);
  387. return obj;
  388. };
  389. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  390. oi.value = generator.getConfig().pandoraSpellSchool;
  391. oi.probability = 2;
  392. if(!oi.templates.empty())
  393. addObjectToRandomPool(oi);
  394. }
  395. // Pandora box with 60 random spells
  396. oi.generateObject = [this]() -> std::shared_ptr<CGObjectInstance>
  397. {
  398. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  399. auto obj = std::dynamic_pointer_cast<CGPandoraBox>(factory->create(map.mapInstance->cb, nullptr));
  400. std::vector <const CSpell *> spells;
  401. for(auto spellID : LIBRARY->spellh->getDefaultAllowed())
  402. {
  403. if(map.isAllowedSpell(spellID))
  404. spells.push_back(spellID.toSpell());
  405. }
  406. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  407. Rewardable::VisitInfo reward;
  408. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  409. {
  410. reward.reward.spells.push_back(spells[j]->id);
  411. }
  412. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  413. obj->configuration.info.push_back(reward);
  414. return obj;
  415. };
  416. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  417. oi.value = generator.getConfig().pandoraSpell60;
  418. oi.probability = 2;
  419. if(!oi.templates.empty())
  420. addObjectToRandomPool(oi);
  421. }
  422. void TreasurePlacer::addSeerHuts()
  423. {
  424. //Seer huts with creatures or generic rewards
  425. ObjectInfo oi(Obj::SEER_HUT, 0);
  426. if(zone.getConnectedZoneIds().size()) //Unlikely, but...
  427. {
  428. auto * qap = zone.getModificator<QuestArtifactPlacer>();
  429. if(!qap)
  430. {
  431. return; //TODO: throw?
  432. }
  433. const int questArtsRemaining = qap->getMaxQuestArtifactCount();
  434. if (!questArtsRemaining)
  435. {
  436. return;
  437. }
  438. //Generate Seer Hut one by one. Duplicated oi possible and should work fine.
  439. oi.maxPerZone = 1;
  440. std::vector<ObjectInfo> possibleSeerHuts;
  441. //14 creatures per town + 4 for each of gold / exp reward
  442. possibleSeerHuts.reserve(14 + 4 + 4);
  443. RandomGeneratorUtil::randomShuffle(creatures, zone.getRand());
  444. auto setRandomArtifact = [qap](CGSeerHut * obj)
  445. {
  446. ArtifactID artid = qap->drawRandomArtifact();
  447. obj->getQuest().mission.artifacts.push_back(artid);
  448. qap->addQuestArtifact(artid);
  449. };
  450. auto destroyObject = [qap](CGObjectInstance & obj)
  451. {
  452. auto & seer = dynamic_cast<CGSeerHut &>(obj);
  453. // Artifact can be used again
  454. ArtifactID artid = seer.getQuest().mission.artifacts.front();
  455. qap->addRandomArtifact(artid);
  456. qap->removeQuestArtifact(artid);
  457. };
  458. for(int i = 0; i < static_cast<int>(creatures.size()); i++)
  459. {
  460. auto * creature = creatures[i];
  461. int creaturesAmount = creatureToCount(creature);
  462. if(!creaturesAmount)
  463. continue;
  464. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  465. // FIXME: Remove duplicated code for gold, exp and creaure reward
  466. oi.generateObject = [cb=map.mapInstance->cb, creature, creaturesAmount, randomAppearance, setRandomArtifact]() -> std::shared_ptr<CGObjectInstance>
  467. {
  468. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  469. auto obj = std::dynamic_pointer_cast<CGSeerHut>(factory->create(cb, nullptr));
  470. Rewardable::VisitInfo reward;
  471. reward.reward.creatures.emplace_back(creature->getId(), creaturesAmount);
  472. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  473. obj->configuration.info.push_back(reward);
  474. setRandomArtifact(obj.get());
  475. return obj;
  476. };
  477. oi.destroyObject = destroyObject;
  478. oi.probability = 3;
  479. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  480. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFactionID())) / map.getTotalZoneCount())) - 4000) / 3);
  481. if (oi.value > zone.getMaxTreasureValue())
  482. {
  483. continue;
  484. }
  485. else
  486. {
  487. if(!oi.templates.empty())
  488. possibleSeerHuts.push_back(oi);
  489. }
  490. }
  491. static const int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  492. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similar
  493. {
  494. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  495. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  496. oi.value = generator.getConfig().questValues[i];
  497. if (oi.value > zone.getMaxTreasureValue())
  498. {
  499. //Both variants have same value
  500. continue;
  501. }
  502. oi.probability = 10;
  503. oi.maxPerZone = 1;
  504. oi.generateObject = [i, randomAppearance, this, setRandomArtifact]() -> std::shared_ptr<CGObjectInstance>
  505. {
  506. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  507. auto obj = std::dynamic_pointer_cast<CGSeerHut>(factory->create(map.mapInstance->cb, nullptr));
  508. Rewardable::VisitInfo reward;
  509. reward.reward.heroExperience = generator.getConfig().questRewardValues[i];
  510. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  511. obj->configuration.info.push_back(reward);
  512. setRandomArtifact(obj.get());
  513. return obj;
  514. };
  515. oi.destroyObject = destroyObject;
  516. if(!oi.templates.empty())
  517. possibleSeerHuts.push_back(oi);
  518. oi.generateObject = [i, randomAppearance, this, setRandomArtifact]() -> std::shared_ptr<CGObjectInstance>
  519. {
  520. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  521. auto obj = std::dynamic_pointer_cast<CGSeerHut>(factory->create(map.mapInstance->cb, nullptr));
  522. Rewardable::VisitInfo reward;
  523. reward.reward.resources[EGameResID::GOLD] = generator.getConfig().questRewardValues[i];
  524. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  525. obj->configuration.info.push_back(reward);
  526. setRandomArtifact(obj.get());
  527. return obj;
  528. };
  529. oi.destroyObject = destroyObject;
  530. if(!oi.templates.empty())
  531. possibleSeerHuts.push_back(oi);
  532. }
  533. if (possibleSeerHuts.empty())
  534. {
  535. return;
  536. }
  537. for (size_t i = 0; i < questArtsRemaining; i++)
  538. {
  539. addObjectToRandomPool(*RandomGeneratorUtil::nextItem(possibleSeerHuts, zone.getRand()));
  540. }
  541. }
  542. }
  543. void TreasurePlacer::setMaxPrisons(size_t count)
  544. {
  545. RecursiveLock lock(externalAccessMutex);
  546. maxPrisons = count;
  547. }
  548. size_t TreasurePlacer::getMaxPrisons() const
  549. {
  550. RecursiveLock lock(externalAccessMutex);
  551. return maxPrisons;
  552. }
  553. int TreasurePlacer::creatureToCount(const CCreature * creature) const
  554. {
  555. if(!creature->getAIValue() || tierValues.empty()) //bug #2681
  556. return 0; //this box won't be generated
  557. //Follow the rules from https://heroes.thelazy.net/index.php/Pandora%27s_Box
  558. int actualTier = creature->getLevel() > tierValues.size() ?
  559. tierValues.size() - 1 :
  560. creature->getLevel() - 1;
  561. float creaturesAmount = std::floor((static_cast<float>(tierValues[actualTier])) / creature->getAIValue());
  562. if (creaturesAmount < 1)
  563. {
  564. return 0;
  565. }
  566. else if(creaturesAmount <= 5)
  567. {
  568. //No change
  569. }
  570. else if(creaturesAmount <= 12)
  571. {
  572. creaturesAmount = std::ceil(creaturesAmount / 2) * 2;
  573. }
  574. else if(creaturesAmount <= 50)
  575. {
  576. creaturesAmount = std::round(creaturesAmount / 5) * 5;
  577. }
  578. else
  579. {
  580. creaturesAmount = std::round(creaturesAmount / 10) * 10;
  581. }
  582. return static_cast<int>(creaturesAmount);
  583. };
  584. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  585. {// no guard in a zone with "monsters: none" and for small treasures; water zones cen get monster strength ZONE_NONE elsewhere if needed
  586. return zone.monsterStrength != EMonsterStrength::ZONE_NONE && value > minGuardedValue;
  587. }
  588. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  589. {
  590. std::vector<ObjectInfo*> objectInfos;
  591. int maxValue = treasureInfo.max;
  592. int minValue = treasureInfo.min;
  593. const ui32 desiredValue = zone.getRand().nextInt(minValue, maxValue);
  594. int currentValue = 0;
  595. bool hasLargeObject = false;
  596. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  597. {
  598. // FIXME: Pointer might be invalidated after this
  599. auto * oi = getRandomObject(desiredValue, currentValue, !hasLargeObject);
  600. if(!oi) //fail
  601. break;
  602. bool visitableFromTop = true;
  603. for(auto & t : oi->templates)
  604. if(!t->isVisitableFromTop())
  605. visitableFromTop = false;
  606. if(visitableFromTop)
  607. {
  608. objectInfos.push_back(oi);
  609. }
  610. else
  611. {
  612. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  613. hasLargeObject = true;
  614. }
  615. //remove from possible objects
  616. assert(oi->maxPerZone);
  617. oi->maxPerZone--;
  618. currentValue += oi->value;
  619. if (currentValue >= minValue)
  620. {
  621. // 50% chance to end right here
  622. if (zone.getRand().nextInt(0, 1) == 1)
  623. break;
  624. }
  625. }
  626. return objectInfos;
  627. }
  628. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  629. {
  630. rmg::Object rmgObject;
  631. for(const auto & oi : treasureInfos)
  632. {
  633. auto blockedArea = rmgObject.getArea();
  634. auto entrableArea = rmgObject.getEntrableArea();
  635. auto accessibleArea = rmgObject.getAccessibleArea();
  636. if(rmgObject.instances().empty())
  637. {
  638. rmgObject.setValue(0);
  639. accessibleArea.add(int3());
  640. }
  641. std::shared_ptr<CGObjectInstance> object = nullptr;
  642. if (oi->generateObject)
  643. {
  644. object = oi->generateObject();
  645. if(oi->templates.empty())
  646. {
  647. logGlobal->warn("Deleting randomized object with no templates: %s", object->getObjectName());
  648. oi->destroyObject(*object);
  649. continue;
  650. }
  651. }
  652. else
  653. {
  654. logGlobal->error("ObjectInfo has no generateObject function! Templates: %d", oi->templates.size());
  655. continue;
  656. }
  657. auto templates = object->getObjectHandler()->getMostSpecificTemplates(zone.getTerrainType());
  658. if (templates.empty())
  659. {
  660. throw rmgException(boost::str(boost::format("Did not find template for object (%d,%d) at %s") % object->ID.getNum() % object->subID.getNum() % zone.getTerrainType().encode(zone.getTerrainType().getNum())));
  661. }
  662. object->appearance = *RandomGeneratorUtil::nextItem(templates, zone.getRand());
  663. //Put object in accessible area next to entrable area (excluding blockvis tiles)
  664. if (!entrableArea.empty())
  665. {
  666. auto entrableBorder = entrableArea.getBorderOutside();
  667. accessibleArea.erase_if([&](const int3 & tile)
  668. {
  669. return !entrableBorder.count(tile);
  670. });
  671. }
  672. auto & instance = rmgObject.addInstance(object);
  673. rmgObject.setValue(rmgObject.getValue() + oi->value);
  674. instance.onCleared = oi->destroyObject;
  675. do
  676. {
  677. if(accessibleArea.empty())
  678. {
  679. //fail - fallback
  680. rmgObject.clear();
  681. return rmgObject;
  682. }
  683. std::vector<int3> bestPositions;
  684. if(densePlacement && !entrableArea.empty())
  685. {
  686. // Choose positon which has access to as many entrable tiles as possible
  687. int bestPositionsWeight = std::numeric_limits<int>::max();
  688. for(const auto & t : accessibleArea.getTilesVector())
  689. {
  690. instance.setPosition(t);
  691. auto currentAccessibleArea = rmgObject.getAccessibleArea();
  692. auto currentEntrableBorder = rmgObject.getEntrableArea().getBorderOutside();
  693. currentAccessibleArea.erase_if([&](const int3 & tile)
  694. {
  695. return !currentEntrableBorder.count(tile);
  696. });
  697. size_t w = currentAccessibleArea.getTilesVector().size();
  698. if(w > bestPositionsWeight)
  699. {
  700. // Minimum 1 position must be entrable
  701. bestPositions.clear();
  702. bestPositions.push_back(t);
  703. bestPositionsWeight = w;
  704. }
  705. else if(w == bestPositionsWeight)
  706. {
  707. bestPositions.push_back(t);
  708. }
  709. }
  710. }
  711. if (bestPositions.empty())
  712. {
  713. bestPositions = accessibleArea.getTilesVector();
  714. }
  715. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, zone.getRand());
  716. instance.setPosition(nextPos - rmgObject.getPosition());
  717. auto instanceAccessibleArea = instance.getAccessibleArea();
  718. if(instance.getBlockedArea().getTilesVector().size() == 1)
  719. {
  720. if(instance.object().appearance->isVisitableFromTop() && !instance.object().isBlockedVisitable())
  721. instanceAccessibleArea.add(instance.getVisitablePosition());
  722. }
  723. //Do not clean up after first object
  724. if(rmgObject.instances().size() == 1)
  725. break;
  726. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  727. break;
  728. //fail - new position
  729. accessibleArea.erase(nextPos);
  730. } while(true);
  731. }
  732. return rmgObject;
  733. }
  734. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, bool allowLargeObjects)
  735. {
  736. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  737. ui32 total = 0;
  738. //calculate actual treasure value range based on remaining value
  739. ui32 maxVal = desiredValue - currentValue;
  740. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  741. for(ObjectInfo & oi : objects.getPossibleObjects()) //copy constructor turned out to be costly
  742. {
  743. if(oi.value > maxVal)
  744. break; //this assumes values are sorted in ascending order
  745. bool visitableFromTop = true;
  746. for(auto & t : oi.templates)
  747. if(!t->isVisitableFromTop())
  748. visitableFromTop = false;
  749. if(!visitableFromTop && !allowLargeObjects)
  750. continue;
  751. if(oi.value >= minValue && oi.maxPerZone > 0)
  752. {
  753. total += oi.probability;
  754. thresholds.emplace_back(total, &oi);
  755. }
  756. }
  757. if(thresholds.empty())
  758. {
  759. return nullptr;
  760. }
  761. else
  762. {
  763. int r = zone.getRand().nextInt(1, total);
  764. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  765. {
  766. return static_cast<int>(rhs.first) < lhs;
  767. };
  768. //binary search = fastest
  769. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  770. return it->second;
  771. }
  772. }
  773. void TreasurePlacer::createTreasures(ObjectManager& manager)
  774. {
  775. const int maxAttempts = 2;
  776. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  777. 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
  778. static const int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  779. minGuardedValue = minGuardedValues[monsterStrength];
  780. const auto blockingGuardMaxValue = zone.getMaxTreasureValue() / 3;
  781. auto valueComparator = [](const CTreasureInfo& lhs, const CTreasureInfo& rhs) -> bool
  782. {
  783. return lhs.max > rhs.max;
  784. };
  785. auto restoreZoneLimits = [](const std::vector<ObjectInfo*>& treasurePile)
  786. {
  787. for (auto* oi : treasurePile)
  788. {
  789. oi->maxPerZone++;
  790. }
  791. };
  792. rmg::Area roads;
  793. auto rp = zone.getModificator<RoadPlacer>();
  794. if (rp)
  795. {
  796. roads = rp->getRoads();
  797. }
  798. rmg::Area nextToRoad(roads.getBorderOutside());
  799. //place biggest treasures first at large distance, place smaller ones inbetween
  800. auto treasureInfo = zone.getTreasureInfo();
  801. boost::sort(treasureInfo, valueComparator);
  802. //sort treasures by ascending value so we can stop checking treasures with too high value
  803. objects.sortPossibleObjects();
  804. const size_t size = zone.area()->getTilesVector().size();
  805. int totalDensity = 0;
  806. // FIXME: No need to use iterator here
  807. for (auto t = treasureInfo.begin(); t != treasureInfo.end(); t++)
  808. {
  809. std::vector<rmg::Object> treasures;
  810. //discard objects with too high value to be ever placed
  811. objects.discardObjectsAboveValue(t->max);
  812. totalDensity += t->density;
  813. const int DENSITY_CONSTANT = 400;
  814. size_t count = (size * t->density) / DENSITY_CONSTANT;
  815. const float minDistance = std::max<float>(std::sqrt(std::min<ui32>(t->min, 30000) / 10.0f / totalDensity), 1.0f);
  816. size_t emergencyLoopFinish = 0;
  817. while(treasures.size() < count && emergencyLoopFinish < count)
  818. {
  819. auto treasurePileInfos = prepareTreasurePile(*t);
  820. if (treasurePileInfos.empty())
  821. {
  822. emergencyLoopFinish++; //Exit potentially infinite loop for bad settings
  823. continue;
  824. }
  825. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0,
  826. [](int v, const ObjectInfo* oi)
  827. {
  828. return v + oi->value;
  829. });
  830. const ui32 maxPileGenerationAttempts = 2;
  831. for (ui32 attempt = 0; attempt < maxPileGenerationAttempts; attempt++)
  832. {
  833. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  834. if (rmgObject.instances().empty())
  835. {
  836. // Restore once if all attempts failed
  837. if (attempt == (maxPileGenerationAttempts - 1))
  838. {
  839. restoreZoneLimits(treasurePileInfos);
  840. }
  841. continue;
  842. }
  843. //guard treasure pile
  844. bool guarded = isGuardNeededForTreasure(value);
  845. if (guarded)
  846. guarded = manager.addGuard(rmgObject, value);
  847. treasures.push_back(rmgObject);
  848. break;
  849. }
  850. }
  851. for (auto& rmgObject : treasures)
  852. {
  853. const bool guarded = rmgObject.isGuarded();
  854. auto path = rmg::Path::invalid();
  855. {
  856. Zone::Lock lock(zone.areaMutex); //We are going to subtract this area
  857. auto searchArea = zone.areaPossible().get();
  858. searchArea.erase_if([this, &minDistance](const int3& tile) -> bool
  859. {
  860. auto ti = map.getTileInfo(tile);
  861. return (ti.getNearestObjectDistance() < minDistance);
  862. });
  863. if (guarded)
  864. {
  865. searchArea.subtract(roads);
  866. path = manager.placeAndConnectObject(searchArea, rmgObject, [this, &rmgObject, &minDistance, &manager, blockingGuardMaxValue, &roads, &nextToRoad](const int3& tile)
  867. {
  868. float bestDistance = 10e9;
  869. for (const auto& t : rmgObject.getArea().getTilesVector())
  870. {
  871. float distance = map.getTileInfo(t).getNearestObjectDistance();
  872. if (distance < minDistance)
  873. return -1.f;
  874. else
  875. vstd::amin(bestDistance, distance);
  876. }
  877. // Guard cannot be adjacent to road, but blocked side of an object could be
  878. if (rmgObject.getValue() > blockingGuardMaxValue && nextToRoad.contains(rmgObject.getGuardPos()))
  879. {
  880. return -1.f;
  881. }
  882. const auto & guardedArea = rmgObject.instances().back()->getAccessibleArea();
  883. const auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  884. if (zone.freePaths()->overlap(areaToBlock) || roads.overlap(areaToBlock) || manager.getVisitableArea().overlap(areaToBlock))
  885. return -1.f;
  886. // Add huge penalty for objects hiding roads
  887. if (rmgObject.getBorderAbove().overlap(roads))
  888. bestDistance /= 10.0f;
  889. return bestDistance;
  890. }, guarded, false, ObjectManager::OptimizeType::BOTH);
  891. }
  892. else
  893. {
  894. // Do not place non-removable objects on roads
  895. if (!rmgObject.getRemovableArea().contains(rmgObject.getArea()))
  896. {
  897. searchArea.subtract(roads);
  898. }
  899. path = manager.placeAndConnectObject(searchArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  900. }
  901. }
  902. if (path.valid())
  903. {
  904. #ifdef TREASURE_PLACER_LOG
  905. treasureArea.unite(rmgObject.getArea());
  906. if (guarded)
  907. {
  908. guards.unite(rmgObject.instances().back()->getBlockedArea());
  909. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  910. auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  911. treasureBlockArea.unite(areaToBlock);
  912. }
  913. #endif
  914. zone.connectPath(path);
  915. manager.placeObject(rmgObject, guarded, true);
  916. }
  917. }
  918. }
  919. }
  920. char TreasurePlacer::dump(const int3 & t)
  921. {
  922. if(guards.contains(t))
  923. return '!';
  924. if(treasureArea.contains(t))
  925. return '$';
  926. if(treasureBlockArea.contains(t))
  927. return '*';
  928. return Modificator::dump(t);
  929. }
  930. void TreasurePlacer::ObjectPool::addObject(const ObjectInfo & info)
  931. {
  932. possibleObjects.push_back(info);
  933. }
  934. void TreasurePlacer::ObjectPool::updateObject(MapObjectID id, MapObjectSubID subid, ObjectInfo info)
  935. {
  936. /*
  937. Handle separately:
  938. - Dwellings
  939. - Prisons
  940. - Seer huts (quests)
  941. - Pandora Boxes
  942. */
  943. // FIXME: This will drop all templates
  944. customObjects.insert(std::make_pair(CompoundMapObjectID(id, subid), info));
  945. }
  946. void TreasurePlacer::ObjectPool::patchWithZoneConfig(const Zone & zone, TreasurePlacer * tp)
  947. {
  948. // FIXME: Wycina wszystkie obiekty poza pandorami i dwellami :?
  949. // Copy standard objects if they are not already modified
  950. /*
  951. for (const auto & object : possibleObjects)
  952. {
  953. for (const auto & templ : object.templates)
  954. {
  955. // FIXME: Objects with same temmplates (Pandora boxes) are not added
  956. CompoundMapObjectID key(templ->id, templ->subid);
  957. if (!vstd::contains(customObjects, key))
  958. {
  959. customObjects[key] = object;
  960. }
  961. }
  962. }
  963. */
  964. auto bannedObjectCategories = zone.getBannedObjectCategories();
  965. auto categoriesSet = std::unordered_set<ObjectConfig::EObjectCategory>(bannedObjectCategories.begin(), bannedObjectCategories.end());
  966. if (categoriesSet.count(ObjectConfig::EObjectCategory::ALL))
  967. {
  968. possibleObjects.clear();
  969. }
  970. else
  971. {
  972. vstd::erase_if(possibleObjects, [this, &categoriesSet](const ObjectInfo & oi) -> bool
  973. {
  974. auto category = getObjectCategory(oi.getCompoundID());
  975. if (categoriesSet.count(category))
  976. {
  977. logGlobal->info("Removing object %s from possible objects", oi.templates.front()->stringID);
  978. return true;
  979. }
  980. return false;
  981. });
  982. auto bannedObjects = zone.getBannedObjects();
  983. auto bannedObjectsSet = std::set<CompoundMapObjectID>(bannedObjects.begin(), bannedObjects.end());
  984. vstd::erase_if(possibleObjects, [&bannedObjectsSet](const ObjectInfo & object)
  985. {
  986. for (const auto & templ : object.templates)
  987. {
  988. CompoundMapObjectID key = object.getCompoundID();
  989. if (bannedObjectsSet.count(key))
  990. {
  991. // FIXME: Stopped working, nothing is banned
  992. logGlobal->info("Banning object %s from possible objects", templ->stringID);
  993. return true;
  994. }
  995. }
  996. return false;
  997. });
  998. }
  999. auto configuredObjects = zone.getConfiguredObjects();
  1000. // FIXME: Access TreasurePlacer from ObjectPool
  1001. for (auto & object : configuredObjects)
  1002. {
  1003. tp->setBasicProperties(object, object.getCompoundID());
  1004. addObject(object);
  1005. logGlobal->info("Added custom object of type %d.%d", object.primaryID, object.secondaryID);
  1006. }
  1007. // TODO: Overwrite or add to possibleObjects
  1008. // FIXME: Protect with mutex as well?
  1009. /*
  1010. for (const auto & customObject : customObjects)
  1011. {
  1012. addObject(customObject.second);
  1013. }
  1014. */
  1015. // TODO: Consider adding custom Pandora boxes with arbitrary content
  1016. }
  1017. std::vector<ObjectInfo> & TreasurePlacer::ObjectPool::getPossibleObjects()
  1018. {
  1019. return possibleObjects;
  1020. }
  1021. void TreasurePlacer::ObjectPool::sortPossibleObjects()
  1022. {
  1023. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  1024. {
  1025. return oi1.value < oi2.value;
  1026. });
  1027. }
  1028. void TreasurePlacer::ObjectPool::discardObjectsAboveValue(ui32 value)
  1029. {
  1030. vstd::erase_if(possibleObjects, [value](const ObjectInfo& oi) -> bool
  1031. {
  1032. return oi.value > value;
  1033. });
  1034. }
  1035. ObjectConfig::EObjectCategory TreasurePlacer::ObjectPool::getObjectCategory(CompoundMapObjectID id)
  1036. {
  1037. auto name = LIBRARY->objtypeh->getObjectHandlerName(id.primaryID);
  1038. if (name == "configurable")
  1039. {
  1040. auto handler = LIBRARY->objtypeh->getHandlerFor(id.primaryID, id.secondaryID);
  1041. if (!handler)
  1042. {
  1043. return ObjectConfig::EObjectCategory::NONE;
  1044. }
  1045. auto temp = handler->getTemplates().front();
  1046. auto info = handler->getObjectInfo(temp);
  1047. if (info->hasGuards())
  1048. {
  1049. return ObjectConfig::EObjectCategory::CREATURE_BANK;
  1050. }
  1051. else if (info->givesResources())
  1052. {
  1053. return ObjectConfig::EObjectCategory::RESOURCE;
  1054. }
  1055. else if (info->givesArtifacts())
  1056. {
  1057. return ObjectConfig::EObjectCategory::RANDOM_ARTIFACT;
  1058. }
  1059. else if (info->givesBonuses())
  1060. {
  1061. return ObjectConfig::EObjectCategory::BONUS;
  1062. }
  1063. return ObjectConfig::EObjectCategory::OTHER;
  1064. }
  1065. else if (name == "dwelling" || name == "randomDwelling")
  1066. {
  1067. // TODO: Special handling for different tiers
  1068. return ObjectConfig::EObjectCategory::DWELLING;
  1069. }
  1070. else if (name == "bank")
  1071. return ObjectConfig::EObjectCategory::CREATURE_BANK;
  1072. else if (name == "market")
  1073. return ObjectConfig::EObjectCategory::OTHER;
  1074. else if (name == "hillFort")
  1075. return ObjectConfig::EObjectCategory::OTHER;
  1076. else if (name == "resource" || name == "randomResource")
  1077. return ObjectConfig::EObjectCategory::RESOURCE;
  1078. else if (name == "randomArtifact") //"artifact"
  1079. return ObjectConfig::EObjectCategory::RANDOM_ARTIFACT;
  1080. else if (name == "artifact")
  1081. {
  1082. if (id.primaryID == Obj::SPELL_SCROLL ) // randomArtifactTreasure
  1083. {
  1084. return ObjectConfig::EObjectCategory::SPELL_SCROLL;
  1085. }
  1086. else
  1087. {
  1088. return ObjectConfig::EObjectCategory::QUEST_ARTIFACT;
  1089. }
  1090. }
  1091. else if (name == "denOfThieves")
  1092. return ObjectConfig::EObjectCategory::OTHER;
  1093. else if (name == "lighthouse")
  1094. {
  1095. return ObjectConfig::EObjectCategory::BONUS;
  1096. }
  1097. else if (name == "magi")
  1098. {
  1099. // TODO: By default, both eye and hut are banned in every zone
  1100. return ObjectConfig::EObjectCategory::OTHER;
  1101. }
  1102. else if (name == "mine")
  1103. return ObjectConfig::EObjectCategory::RESOURCE_GENERATOR;
  1104. else if (name == "pandora")
  1105. return ObjectConfig::EObjectCategory::PANDORAS_BOX;
  1106. else if (name == "prison")
  1107. {
  1108. // TODO: Prisons should be configurable
  1109. return ObjectConfig::EObjectCategory::OTHER;
  1110. }
  1111. else if (name == "questArtifact")
  1112. {
  1113. // TODO: There are no dedicated quest artifacts, needs extra logic
  1114. return ObjectConfig::EObjectCategory::QUEST_ARTIFACT;
  1115. }
  1116. else if (name == "seerHut")
  1117. {
  1118. return ObjectConfig::EObjectCategory::SEER_HUT;
  1119. }
  1120. else if (name == "siren")
  1121. return ObjectConfig::EObjectCategory::BONUS;
  1122. else if (name == "obelisk")
  1123. return ObjectConfig::EObjectCategory::OTHER;
  1124. // TODO: ObjectConfig::EObjectCategory::SPELL_SCROLL
  1125. // Not interesting for us
  1126. return ObjectConfig::EObjectCategory::NONE;
  1127. }
  1128. VCMI_LIB_NAMESPACE_END