TreasurePlacer.cpp 40 KB

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