TreasurePlacer.cpp 38 KB

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