CArtHandler.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  1. /*
  2. * CArtHandler.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 "CArtHandler.h"
  12. #include "filesystem/Filesystem.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "CModHandler.h"
  16. #include "GameSettings.h"
  17. #include "CCreatureHandler.h"
  18. #include "spells/CSpellHandler.h"
  19. #include "mapObjects/MapObjects.h"
  20. #include "NetPacksBase.h"
  21. #include "StringConstants.h"
  22. #include "CRandomGenerator.h"
  23. #include "mapObjects/CObjectClassesHandler.h"
  24. #include "mapping/CMap.h"
  25. #include "serializer/JsonSerializeFormat.h"
  26. // Note: list must match entries in ArtTraits.txt
  27. #define ART_POS_LIST \
  28. ART_POS(SPELLBOOK) \
  29. ART_POS(MACH4) \
  30. ART_POS(MACH3) \
  31. ART_POS(MACH2) \
  32. ART_POS(MACH1) \
  33. ART_POS(MISC5) \
  34. ART_POS(MISC4) \
  35. ART_POS(MISC3) \
  36. ART_POS(MISC2) \
  37. ART_POS(MISC1) \
  38. ART_POS(FEET) \
  39. ART_POS(LEFT_RING) \
  40. ART_POS(RIGHT_RING) \
  41. ART_POS(TORSO) \
  42. ART_POS(LEFT_HAND) \
  43. ART_POS(RIGHT_HAND) \
  44. ART_POS(NECK) \
  45. ART_POS(SHOULDERS) \
  46. ART_POS(HEAD)
  47. VCMI_LIB_NAMESPACE_BEGIN
  48. int32_t CArtifact::getIndex() const
  49. {
  50. return id.toEnum();
  51. }
  52. int32_t CArtifact::getIconIndex() const
  53. {
  54. return iconIndex;
  55. }
  56. std::string CArtifact::getJsonKey() const
  57. {
  58. return modScope + ':' + identifier;
  59. }
  60. void CArtifact::registerIcons(const IconRegistar & cb) const
  61. {
  62. cb(getIconIndex(), 0, "ARTIFACT", image);
  63. cb(getIconIndex(), 0, "ARTIFACTLARGE", large);
  64. }
  65. ArtifactID CArtifact::getId() const
  66. {
  67. return id;
  68. }
  69. const IBonusBearer * CArtifact::getBonusBearer() const
  70. {
  71. return this;
  72. }
  73. std::string CArtifact::getDescriptionTranslated() const
  74. {
  75. return VLC->generaltexth->translate(getDescriptionTextID());
  76. }
  77. std::string CArtifact::getEventTranslated() const
  78. {
  79. return VLC->generaltexth->translate(getEventTextID());
  80. }
  81. std::string CArtifact::getNameTranslated() const
  82. {
  83. return VLC->generaltexth->translate(getNameTextID());
  84. }
  85. std::string CArtifact::getDescriptionTextID() const
  86. {
  87. return TextIdentifier("artifact", modScope, identifier, "description").get();
  88. }
  89. std::string CArtifact::getEventTextID() const
  90. {
  91. return TextIdentifier("artifact", modScope, identifier, "event").get();
  92. }
  93. std::string CArtifact::getNameTextID() const
  94. {
  95. return TextIdentifier("artifact", modScope, identifier, "name").get();
  96. }
  97. uint32_t CArtifact::getPrice() const
  98. {
  99. return price;
  100. }
  101. CreatureID CArtifact::getWarMachine() const
  102. {
  103. return warMachine;
  104. }
  105. bool CArtifact::isBig() const
  106. {
  107. return warMachine != CreatureID::NONE;
  108. }
  109. bool CArtifact::isTradable() const
  110. {
  111. switch(id)
  112. {
  113. case ArtifactID::SPELLBOOK:
  114. case ArtifactID::GRAIL:
  115. return false;
  116. default:
  117. return !isBig();
  118. }
  119. }
  120. bool CArtifact::canBeDisassembled() const
  121. {
  122. return !(constituents == nullptr);
  123. }
  124. bool CArtifact::canBePutAt(const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  125. {
  126. auto simpleArtCanBePutAt = [this](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  127. {
  128. if(ArtifactUtils::isSlotBackpack(slot))
  129. {
  130. if(isBig() || !ArtifactUtils::isBackpackFreeSlots(artSet))
  131. return false;
  132. return true;
  133. }
  134. if(!vstd::contains(possibleSlots.at(artSet->bearerType()), slot))
  135. return false;
  136. return artSet->isPositionFree(slot, assumeDestRemoved);
  137. };
  138. auto artCanBePutAt = [this, simpleArtCanBePutAt](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  139. {
  140. if(canBeDisassembled())
  141. {
  142. if(!simpleArtCanBePutAt(artSet, slot, assumeDestRemoved))
  143. return false;
  144. if(ArtifactUtils::isSlotBackpack(slot))
  145. return true;
  146. CArtifactFittingSet fittingSet(artSet->bearerType());
  147. fittingSet.artifactsWorn = artSet->artifactsWorn;
  148. if(assumeDestRemoved)
  149. fittingSet.removeArtifact(slot);
  150. assert(constituents);
  151. for(const auto art : *constituents)
  152. {
  153. auto possibleSlot = ArtifactUtils::getArtAnyPosition(&fittingSet, art->getId());
  154. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  155. {
  156. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  157. }
  158. else
  159. {
  160. return false;
  161. }
  162. }
  163. return true;
  164. }
  165. else
  166. {
  167. return simpleArtCanBePutAt(artSet, slot, assumeDestRemoved);
  168. }
  169. };
  170. if(slot == ArtifactPosition::TRANSITION_POS)
  171. return true;
  172. if(slot == ArtifactPosition::FIRST_AVAILABLE)
  173. {
  174. for(const auto & slot : possibleSlots.at(artSet->bearerType()))
  175. {
  176. if(artCanBePutAt(artSet, slot, assumeDestRemoved))
  177. return true;
  178. }
  179. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  180. }
  181. else if(ArtifactUtils::isSlotBackpack(slot))
  182. {
  183. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  184. }
  185. else
  186. {
  187. return artCanBePutAt(artSet, slot, assumeDestRemoved);
  188. }
  189. }
  190. CArtifact::CArtifact()
  191. {
  192. setNodeType(ARTIFACT);
  193. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  194. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  195. possibleSlots[ArtBearer::COMMANDER];
  196. }
  197. //This destructor should be placed here to avoid side effects
  198. CArtifact::~CArtifact() = default;
  199. int CArtifact::getArtClassSerial() const
  200. {
  201. if(id == ArtifactID::SPELL_SCROLL)
  202. return 4;
  203. switch(aClass)
  204. {
  205. case ART_TREASURE:
  206. return 0;
  207. case ART_MINOR:
  208. return 1;
  209. case ART_MAJOR:
  210. return 2;
  211. case ART_RELIC:
  212. return 3;
  213. case ART_SPECIAL:
  214. return 5;
  215. }
  216. return -1;
  217. }
  218. std::string CArtifact::nodeName() const
  219. {
  220. return "Artifact: " + getNameTranslated();
  221. }
  222. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  223. {
  224. b->source = Bonus::ARTIFACT;
  225. b->duration = Bonus::PERMANENT;
  226. b->description = getNameTranslated();
  227. CBonusSystemNode::addNewBonus(b);
  228. }
  229. void CArtifact::updateFrom(const JsonNode& data)
  230. {
  231. //TODO:CArtifact::updateFrom
  232. }
  233. void CArtifact::serializeJson(JsonSerializeFormat & handler)
  234. {
  235. }
  236. void CGrowingArtifact::levelUpArtifact (CArtifactInstance * art)
  237. {
  238. auto b = std::make_shared<Bonus>();
  239. b->type = Bonus::LEVEL_COUNTER;
  240. b->val = 1;
  241. b->duration = Bonus::COMMANDER_KILLED;
  242. art->accumulateBonus(b);
  243. for(const auto & bonus : bonusesPerLevel)
  244. {
  245. if (art->valOfBonuses(Bonus::LEVEL_COUNTER) % bonus.first == 0) //every n levels
  246. {
  247. art->accumulateBonus(std::make_shared<Bonus>(bonus.second));
  248. }
  249. }
  250. for(const auto & bonus : thresholdBonuses)
  251. {
  252. if (art->valOfBonuses(Bonus::LEVEL_COUNTER) == bonus.first) //every n levels
  253. {
  254. art->addNewBonus(std::make_shared<Bonus>(bonus.second));
  255. }
  256. }
  257. }
  258. CArtHandler::~CArtHandler() = default;
  259. std::vector<JsonNode> CArtHandler::loadLegacyData()
  260. {
  261. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_ARTIFACT);
  262. objects.resize(dataSize);
  263. std::vector<JsonNode> h3Data;
  264. h3Data.reserve(dataSize);
  265. #define ART_POS(x) #x ,
  266. const std::vector<std::string> artSlots = { ART_POS_LIST };
  267. #undef ART_POS
  268. static std::map<char, std::string> classes =
  269. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  270. CLegacyConfigParser parser("DATA/ARTRAITS.TXT");
  271. CLegacyConfigParser events("DATA/ARTEVENT.TXT");
  272. parser.endLine(); // header
  273. parser.endLine();
  274. for (size_t i = 0; i < dataSize; i++)
  275. {
  276. JsonNode artData;
  277. artData["text"]["name"].String() = parser.readString();
  278. artData["text"]["event"].String() = events.readString();
  279. artData["value"].Float() = parser.readNumber();
  280. for(const auto & artSlot : artSlots)
  281. {
  282. if(parser.readString() == "x")
  283. {
  284. artData["slot"].Vector().push_back(JsonNode());
  285. artData["slot"].Vector().back().String() = artSlot;
  286. }
  287. }
  288. artData["class"].String() = classes[parser.readString()[0]];
  289. artData["text"]["description"].String() = parser.readString();
  290. parser.endLine();
  291. events.endLine();
  292. h3Data.push_back(artData);
  293. }
  294. return h3Data;
  295. }
  296. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  297. {
  298. auto * object = loadFromJson(scope, data, name, objects.size());
  299. object->iconIndex = object->getIndex() + 5;
  300. objects.emplace_back(object);
  301. registerObject(scope, "artifact", name, object->id);
  302. }
  303. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  304. {
  305. auto * object = loadFromJson(scope, data, name, index);
  306. object->iconIndex = object->getIndex();
  307. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  308. objects[index] = object;
  309. registerObject(scope, "artifact", name, object->id);
  310. }
  311. const std::vector<std::string> & CArtHandler::getTypeNames() const
  312. {
  313. static const std::vector<std::string> typeNames = { "artifact" };
  314. return typeNames;
  315. }
  316. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  317. {
  318. assert(identifier.find(':') == std::string::npos);
  319. assert(!scope.empty());
  320. CArtifact * art = nullptr;
  321. if(!VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS) || node["growing"].isNull())
  322. {
  323. art = new CArtifact();
  324. }
  325. else
  326. {
  327. auto * growing = new CGrowingArtifact();
  328. loadGrowingArt(growing, node);
  329. art = growing;
  330. }
  331. art->id = ArtifactID(index);
  332. art->identifier = identifier;
  333. art->modScope = scope;
  334. const JsonNode & text = node["text"];
  335. VLC->generaltexth->registerString(scope, art->getNameTextID(), text["name"].String());
  336. VLC->generaltexth->registerString(scope, art->getDescriptionTextID(), text["description"].String());
  337. VLC->generaltexth->registerString(scope, art->getEventTextID(), text["event"].String());
  338. const JsonNode & graphics = node["graphics"];
  339. art->image = graphics["image"].String();
  340. if(!graphics["large"].isNull())
  341. art->large = graphics["large"].String();
  342. else
  343. art->large = art->image;
  344. art->advMapDef = graphics["map"].String();
  345. art->price = static_cast<ui32>(node["value"].Float());
  346. loadSlots(art, node);
  347. loadClass(art, node);
  348. loadType(art, node);
  349. loadComponents(art, node);
  350. for(const auto & b : node["bonuses"].Vector())
  351. {
  352. auto bonus = JsonUtils::parseBonus(b);
  353. art->addNewBonus(bonus);
  354. }
  355. const JsonNode & warMachine = node["warMachine"];
  356. if(warMachine.getType() == JsonNode::JsonType::DATA_STRING && !warMachine.String().empty())
  357. {
  358. VLC->modh->identifiers.requestIdentifier("creature", warMachine, [=](si32 id)
  359. {
  360. art->warMachine = CreatureID(id);
  361. //this assumes that creature object is stored before registration
  362. VLC->creh->objects.at(id)->warMachine = art->id;
  363. });
  364. }
  365. VLC->modh->identifiers.requestIdentifier(scope, "object", "artifact", [=](si32 index)
  366. {
  367. JsonNode conf;
  368. conf.setMeta(scope);
  369. VLC->objtypeh->loadSubObject(art->identifier, conf, Obj::ARTIFACT, art->getIndex());
  370. if(!art->advMapDef.empty())
  371. {
  372. JsonNode templ;
  373. templ["animation"].String() = art->advMapDef;
  374. templ.setMeta(scope);
  375. // add new template.
  376. // Necessary for objects added via mods that don't have any templates in H3
  377. VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->addTemplate(templ);
  378. }
  379. // object does not have any templates - this is not usable object (e.g. pseudo-art like lock)
  380. if(VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->getTemplates().empty())
  381. VLC->objtypeh->removeSubObject(Obj::ARTIFACT, art->getIndex());
  382. });
  383. return art;
  384. }
  385. ArtifactPosition::ArtifactPosition(std::string slotName):
  386. num(ArtifactPosition::PRE_FIRST)
  387. {
  388. #define ART_POS(x) { #x, ArtifactPosition::x },
  389. static const std::map<std::string, ArtifactPosition> artifactPositionMap = { ART_POS_LIST };
  390. #undef ART_POS
  391. auto it = artifactPositionMap.find (slotName);
  392. if (it != artifactPositionMap.end())
  393. num = it->second;
  394. else
  395. logMod->warn("Warning! Artifact slot %s not recognized!", slotName);
  396. }
  397. void CArtHandler::addSlot(CArtifact * art, const std::string & slotID) const
  398. {
  399. static const std::vector<ArtifactPosition> miscSlots =
  400. {
  401. ArtifactPosition::MISC1, ArtifactPosition::MISC2, ArtifactPosition::MISC3, ArtifactPosition::MISC4, ArtifactPosition::MISC5
  402. };
  403. static const std::vector<ArtifactPosition> ringSlots =
  404. {
  405. ArtifactPosition::RIGHT_RING, ArtifactPosition::LEFT_RING
  406. };
  407. if (slotID == "MISC")
  408. {
  409. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], miscSlots);
  410. }
  411. else if (slotID == "RING")
  412. {
  413. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], ringSlots);
  414. }
  415. else
  416. {
  417. auto slot = ArtifactPosition(slotID);
  418. if (slot != ArtifactPosition::PRE_FIRST)
  419. art->possibleSlots[ArtBearer::HERO].push_back(slot);
  420. }
  421. }
  422. void CArtHandler::loadSlots(CArtifact * art, const JsonNode & node) const
  423. {
  424. if (!node["slot"].isNull()) //we assume non-hero slots are irrelevant?
  425. {
  426. if (node["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  427. addSlot(art, node["slot"].String());
  428. else
  429. {
  430. for (const JsonNode & slot : node["slot"].Vector())
  431. addSlot(art, slot.String());
  432. }
  433. std::sort(art->possibleSlots.at(ArtBearer::HERO).begin(), art->possibleSlots.at(ArtBearer::HERO).end());
  434. }
  435. }
  436. CArtifact::EartClass CArtHandler::stringToClass(const std::string & className)
  437. {
  438. static const std::map<std::string, CArtifact::EartClass> artifactClassMap =
  439. {
  440. {"TREASURE", CArtifact::ART_TREASURE},
  441. {"MINOR", CArtifact::ART_MINOR},
  442. {"MAJOR", CArtifact::ART_MAJOR},
  443. {"RELIC", CArtifact::ART_RELIC},
  444. {"SPECIAL", CArtifact::ART_SPECIAL}
  445. };
  446. auto it = artifactClassMap.find (className);
  447. if (it != artifactClassMap.end())
  448. return it->second;
  449. logMod->warn("Warning! Artifact rarity %s not recognized!", className);
  450. return CArtifact::ART_SPECIAL;
  451. }
  452. void CArtHandler::loadClass(CArtifact * art, const JsonNode & node) const
  453. {
  454. art->aClass = stringToClass(node["class"].String());
  455. }
  456. void CArtHandler::loadType(CArtifact * art, const JsonNode & node) const
  457. {
  458. #define ART_BEARER(x) { #x, ArtBearer::x },
  459. static const std::map<std::string, int> artifactBearerMap = { ART_BEARER_LIST };
  460. #undef ART_BEARER
  461. for (const JsonNode & b : node["type"].Vector())
  462. {
  463. auto it = artifactBearerMap.find (b.String());
  464. if (it != artifactBearerMap.end())
  465. {
  466. int bearerType = it->second;
  467. switch (bearerType)
  468. {
  469. case ArtBearer::HERO://TODO: allow arts having several possible bearers
  470. break;
  471. case ArtBearer::COMMANDER:
  472. makeItCommanderArt (art); //original artifacts should have only one bearer type
  473. break;
  474. case ArtBearer::CREATURE:
  475. makeItCreatureArt (art);
  476. break;
  477. }
  478. }
  479. else
  480. logMod->warn("Warning! Artifact type %s not recognized!", b.String());
  481. }
  482. }
  483. void CArtHandler::loadComponents(CArtifact * art, const JsonNode & node)
  484. {
  485. if (!node["components"].isNull())
  486. {
  487. art->constituents = std::make_unique<std::vector<CArtifact *>>();
  488. for(const auto & component : node["components"].Vector())
  489. {
  490. VLC->modh->identifiers.requestIdentifier("artifact", component, [=](si32 id)
  491. {
  492. // when this code is called both combinational art as well as component are loaded
  493. // so it is safe to access any of them
  494. art->constituents->push_back(objects[id]);
  495. objects[id]->constituentOf.push_back(art);
  496. });
  497. }
  498. }
  499. }
  500. void CArtHandler::loadGrowingArt(CGrowingArtifact * art, const JsonNode & node) const
  501. {
  502. for (auto b : node["growing"]["bonusesPerLevel"].Vector())
  503. {
  504. art->bonusesPerLevel.emplace_back(static_cast<ui16>(b["level"].Float()), Bonus());
  505. JsonUtils::parseBonus(b["bonus"], &art->bonusesPerLevel.back().second);
  506. }
  507. for (auto b : node["growing"]["thresholdBonuses"].Vector())
  508. {
  509. art->thresholdBonuses.emplace_back(static_cast<ui16>(b["level"].Float()), Bonus());
  510. JsonUtils::parseBonus(b["bonus"], &art->thresholdBonuses.back().second);
  511. }
  512. }
  513. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags, std::function<bool(ArtifactID)> accepts)
  514. {
  515. auto getAllowedArts = [&](std::vector<ConstTransitivePtr<CArtifact> > &out, std::vector<CArtifact*> *arts, CArtifact::EartClass flag)
  516. {
  517. if (arts->empty()) //restock available arts
  518. fillList(*arts, flag);
  519. for (auto & arts_i : *arts)
  520. {
  521. if (accepts(arts_i->id))
  522. {
  523. CArtifact *art = arts_i;
  524. out.emplace_back(art);
  525. }
  526. }
  527. };
  528. auto getAllowed = [&](std::vector<ConstTransitivePtr<CArtifact> > &out)
  529. {
  530. if (flags & CArtifact::ART_TREASURE)
  531. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  532. if (flags & CArtifact::ART_MINOR)
  533. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  534. if (flags & CArtifact::ART_MAJOR)
  535. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  536. if (flags & CArtifact::ART_RELIC)
  537. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  538. if(out.empty()) //no artifact of specified rarity, we need to take another one
  539. {
  540. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  541. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  542. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  543. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  544. }
  545. if(out.empty()) //no arts are available at all
  546. {
  547. out.resize (64);
  548. std::fill_n (out.begin(), 64, objects[2]); //Give Grail - this can't be banned (hopefully)
  549. }
  550. };
  551. std::vector<ConstTransitivePtr<CArtifact> > out;
  552. getAllowed(out);
  553. ArtifactID artID = (*RandomGeneratorUtil::nextItem(out, rand))->id;
  554. erasePickedArt(artID);
  555. return artID;
  556. }
  557. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::function<bool(ArtifactID)> accepts)
  558. {
  559. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  560. }
  561. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags)
  562. {
  563. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  564. }
  565. void CArtHandler::makeItCreatureArt(CArtifact * a, bool onlyCreature)
  566. {
  567. if (onlyCreature)
  568. {
  569. a->possibleSlots[ArtBearer::HERO].clear();
  570. a->possibleSlots[ArtBearer::COMMANDER].clear();
  571. }
  572. a->possibleSlots[ArtBearer::CREATURE].push_back(ArtifactPosition::CREATURE_SLOT);
  573. }
  574. void CArtHandler::makeItCommanderArt(CArtifact * a, bool onlyCommander)
  575. {
  576. if (onlyCommander)
  577. {
  578. a->possibleSlots[ArtBearer::HERO].clear();
  579. a->possibleSlots[ArtBearer::CREATURE].clear();
  580. }
  581. for (int i = ArtifactPosition::COMMANDER1; i <= ArtifactPosition::COMMANDER6; ++i)
  582. a->possibleSlots[ArtBearer::COMMANDER].push_back(ArtifactPosition(i));
  583. }
  584. bool CArtHandler::legalArtifact(const ArtifactID & id)
  585. {
  586. auto art = objects[id];
  587. //assert ( (!art->constituents) || art->constituents->size() ); //artifacts is not combined or has some components
  588. if(art->constituents)
  589. return false; //no combo artifacts spawning
  590. if(art->aClass < CArtifact::ART_TREASURE || art->aClass > CArtifact::ART_RELIC)
  591. return false; // invalid class
  592. if(!art->possibleSlots[ArtBearer::HERO].empty())
  593. return true;
  594. if(!art->possibleSlots[ArtBearer::CREATURE].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_ARTIFACT))
  595. return true;
  596. if(!art->possibleSlots[ArtBearer::COMMANDER].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS))
  597. return true;
  598. return false;
  599. }
  600. void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
  601. {
  602. allowedArtifacts.clear();
  603. treasures.clear();
  604. minors.clear();
  605. majors.clear();
  606. relics.clear();
  607. for (ArtifactID i=ArtifactID::SPELLBOOK; i<ArtifactID::ART_SELECTION; i.advance(1))
  608. {
  609. //check artifacts allowed on a map
  610. //TODO: This line will be different when custom map format is implemented
  611. if (allowed[i] && legalArtifact(i))
  612. allowedArtifacts.push_back(objects[i]);
  613. }
  614. for(ArtifactID i = ArtifactID::ART_SELECTION; i < ArtifactID(static_cast<si32>(objects.size())); i.advance(1)) //try to allow all artifacts added by mods
  615. {
  616. if (legalArtifact(ArtifactID(i)))
  617. allowedArtifacts.push_back(objects[i]);
  618. //keep im mind that artifact can be worn by more than one type of bearer
  619. }
  620. }
  621. std::vector<bool> CArtHandler::getDefaultAllowed() const
  622. {
  623. std::vector<bool> allowedArtifacts;
  624. allowedArtifacts.resize(127, true);
  625. allowedArtifacts.resize(141, false);
  626. allowedArtifacts.resize(size(), true);
  627. return allowedArtifacts;
  628. }
  629. void CArtHandler::erasePickedArt(const ArtifactID & id)
  630. {
  631. CArtifact *art = objects[id];
  632. if(auto artifactList = listFromClass(art->aClass))
  633. {
  634. if(artifactList->empty())
  635. fillList(*artifactList, art->aClass);
  636. auto itr = vstd::find(*artifactList, art);
  637. if(itr != artifactList->end())
  638. {
  639. artifactList->erase(itr);
  640. }
  641. else
  642. logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
  643. }
  644. else
  645. logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
  646. }
  647. boost::optional<std::vector<CArtifact*>&> CArtHandler::listFromClass( CArtifact::EartClass artifactClass )
  648. {
  649. switch(artifactClass)
  650. {
  651. case CArtifact::ART_TREASURE:
  652. return treasures;
  653. case CArtifact::ART_MINOR:
  654. return minors;
  655. case CArtifact::ART_MAJOR:
  656. return majors;
  657. case CArtifact::ART_RELIC:
  658. return relics;
  659. default: //special artifacts should not be erased
  660. return boost::optional<std::vector<CArtifact*>&>();
  661. }
  662. }
  663. void CArtHandler::fillList( std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass )
  664. {
  665. assert(listToBeFilled.empty());
  666. for (auto & elem : allowedArtifacts)
  667. {
  668. if (elem->aClass == artifactClass)
  669. listToBeFilled.push_back(elem);
  670. }
  671. }
  672. void CArtHandler::afterLoadFinalization()
  673. {
  674. //All artifacts have their id, so we can properly update their bonuses' source ids.
  675. for(auto &art : objects)
  676. {
  677. for(auto &bonus : art->getExportedBonusList())
  678. {
  679. assert(art == objects[art->id]);
  680. assert(bonus->source == Bonus::ARTIFACT);
  681. bonus->sid = art->id;
  682. }
  683. }
  684. CBonusSystemNode::treeHasChanged();
  685. }
  686. CArtifactInstance::CArtifactInstance()
  687. {
  688. init();
  689. }
  690. CArtifactInstance::CArtifactInstance( CArtifact *Art)
  691. {
  692. init();
  693. setType(Art);
  694. }
  695. void CArtifactInstance::setType( CArtifact *Art )
  696. {
  697. artType = Art;
  698. attachTo(*Art);
  699. }
  700. std::string CArtifactInstance::nodeName() const
  701. {
  702. return "Artifact instance of " + (artType ? artType->getJsonKey() : std::string("uninitialized")) + " type";
  703. }
  704. CArtifactInstance * CArtifactInstance::createScroll(const SpellID & sid)
  705. {
  706. auto * ret = new CArtifactInstance(VLC->arth->objects[ArtifactID::SPELL_SCROLL]);
  707. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::SPELL, Bonus::ARTIFACT_INSTANCE, -1, ArtifactID::SPELL_SCROLL, sid);
  708. ret->addNewBonus(b);
  709. return ret;
  710. }
  711. void CArtifactInstance::init()
  712. {
  713. id = ArtifactInstanceID();
  714. id = static_cast<ArtifactInstanceID>(ArtifactID::NONE); //to be randomized
  715. setNodeType(ARTIFACT_INSTANCE);
  716. }
  717. std::string CArtifactInstance::getEffectiveDescription(const CGHeroInstance * hero) const
  718. {
  719. std::string text = artType->getDescriptionTranslated();
  720. if (!vstd::contains(text, '{'))
  721. text = '{' + artType->getNameTranslated() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style
  722. if(artType->getId() == ArtifactID::SPELL_SCROLL)
  723. {
  724. // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll.
  725. // so we want to replace text in [...] with a spell name
  726. // however other language versions don't have name placeholder at all, so we have to be careful
  727. SpellID spellID = getGivenSpellID();
  728. size_t nameStart = text.find_first_of('[');
  729. size_t nameEnd = text.find_first_of(']', nameStart);
  730. if(spellID.getNum() >= 0)
  731. {
  732. if(nameStart != std::string::npos && nameEnd != std::string::npos)
  733. text = text.replace(nameStart, nameEnd - nameStart + 1, spellID.toSpell(VLC->spells())->getNameTranslated());
  734. }
  735. }
  736. else if(hero && !artType->constituentOf.empty()) //display info about set
  737. {
  738. std::string artList;
  739. auto * combinedArt = artType->constituentOf[0];
  740. text += "\n\n";
  741. text += "{" + combinedArt->getNameTranslated() + "}";
  742. int wornArtifacts = 0;
  743. for(auto * a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set?
  744. {
  745. artList += "\n" + a->getNameTranslated();
  746. if (hero->hasArt(a->getId(), true))
  747. wornArtifacts++;
  748. }
  749. text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " +
  750. boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList;
  751. //TODO: fancy colors and fonts for this text
  752. }
  753. return text;
  754. }
  755. ArtifactID CArtifactInstance::getTypeId() const
  756. {
  757. return artType->getId();
  758. }
  759. bool CArtifactInstance::canBePutAt(const ArtifactLocation & al, bool assumeDestRemoved) const
  760. {
  761. return artType->canBePutAt(al.getHolderArtSet(), al.slot, assumeDestRemoved);
  762. }
  763. void CArtifactInstance::putAt(ArtifactLocation al)
  764. {
  765. assert(canBePutAt(al));
  766. al.getHolderArtSet()->setNewArtSlot(al.slot, this, false);
  767. if(ArtifactUtils::isSlotEquipment(al.slot))
  768. al.getHolderNode()->attachTo(*this);
  769. }
  770. void CArtifactInstance::removeFrom(ArtifactLocation al)
  771. {
  772. assert(al.getHolderArtSet()->getArt(al.slot) == this);
  773. al.getHolderArtSet()->eraseArtSlot(al.slot);
  774. if(ArtifactUtils::isSlotEquipment(al.slot))
  775. al.getHolderNode()->detachFrom(*this);
  776. }
  777. bool CArtifactInstance::canBeDisassembled() const
  778. {
  779. return artType->canBeDisassembled();
  780. }
  781. std::vector<const CArtifact *> CArtifactInstance::assemblyPossibilities(const CArtifactSet * h, bool equipped) const
  782. {
  783. std::vector<const CArtifact *> ret;
  784. if(artType->constituents) //combined artifact already: no combining of combined artifacts... for now.
  785. return ret;
  786. for(const auto * artifact : artType->constituentOf)
  787. {
  788. assert(artifact->constituents);
  789. bool possible = true;
  790. for(const auto * constituent : *artifact->constituents) //check if all constituents are available
  791. {
  792. if(equipped)
  793. {
  794. // Search for equipped arts
  795. if (!h->hasArt(constituent->getId(), true, false, false))
  796. {
  797. possible = false;
  798. break;
  799. }
  800. }
  801. else
  802. {
  803. // Search in backpack
  804. if(!h->hasArtBackpack(constituent->getId()))
  805. {
  806. possible = false;
  807. break;
  808. }
  809. }
  810. }
  811. if(possible)
  812. ret.push_back(artifact);
  813. }
  814. return ret;
  815. }
  816. void CArtifactInstance::move(const ArtifactLocation & src, const ArtifactLocation & dst)
  817. {
  818. removeFrom(src);
  819. putAt(dst);
  820. }
  821. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(CArtifact *Art)
  822. {
  823. if(!Art->constituents)
  824. {
  825. auto * ret = new CArtifactInstance(Art);
  826. if (dynamic_cast<CGrowingArtifact *>(Art))
  827. {
  828. auto bonus = std::make_shared<Bonus>();
  829. bonus->type = Bonus::LEVEL_COUNTER;
  830. bonus->val = 0;
  831. ret->addNewBonus (bonus);
  832. }
  833. return ret;
  834. }
  835. else
  836. {
  837. auto * ret = new CCombinedArtifactInstance(Art);
  838. ret->createConstituents();
  839. return ret;
  840. }
  841. }
  842. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(const ArtifactID & aid)
  843. {
  844. return createNewArtifactInstance(VLC->arth->objects[aid]);
  845. }
  846. CArtifactInstance * CArtifactInstance::createArtifact(CMap * map, const ArtifactID & aid, int spellID)
  847. {
  848. CArtifactInstance * a = nullptr;
  849. if(aid >= 0)
  850. {
  851. if(spellID < 0)
  852. {
  853. a = CArtifactInstance::createNewArtifactInstance(aid);
  854. }
  855. else
  856. {
  857. a = CArtifactInstance::createScroll(SpellID(spellID));
  858. }
  859. }
  860. else //FIXME: create combined artifact instance for random combined artifacts, just in case
  861. {
  862. a = new CArtifactInstance(); //random, empty
  863. }
  864. map->addNewArtifactInstance(a);
  865. //TODO make it nicer
  866. if(a->artType && (!!a->artType->constituents))
  867. {
  868. auto * comb = dynamic_cast<CCombinedArtifactInstance *>(a);
  869. for(CCombinedArtifactInstance::ConstituentInfo & ci : comb->constituentsInfo)
  870. {
  871. map->addNewArtifactInstance(ci.art);
  872. }
  873. }
  874. return a;
  875. }
  876. void CArtifactInstance::deserializationFix()
  877. {
  878. setType(artType);
  879. }
  880. SpellID CArtifactInstance::getGivenSpellID() const
  881. {
  882. const auto b = getBonusLocalFirst(Selector::type()(Bonus::SPELL));
  883. if(!b)
  884. {
  885. logMod->warn("Warning: %s doesn't bear any spell!", nodeName());
  886. return SpellID::NONE;
  887. }
  888. return SpellID(b->subtype);
  889. }
  890. bool CArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  891. {
  892. return supposedPart == this;
  893. }
  894. CCombinedArtifactInstance::CCombinedArtifactInstance(CArtifact *Art)
  895. : CArtifactInstance(Art) //TODO: seems unused, but need to be written
  896. {
  897. }
  898. void CCombinedArtifactInstance::createConstituents()
  899. {
  900. assert(artType);
  901. assert(artType->constituents);
  902. for(const CArtifact * art : *artType->constituents)
  903. {
  904. addAsConstituent(CArtifactInstance::createNewArtifactInstance(art->getId()), ArtifactPosition::PRE_FIRST);
  905. }
  906. }
  907. void CCombinedArtifactInstance::addAsConstituent(CArtifactInstance * art, const ArtifactPosition & slot)
  908. {
  909. assert(vstd::contains_if(*artType->constituents, [=](const CArtifact * constituent){
  910. return constituent->getId() == art->artType->getId();
  911. }));
  912. assert(art->getParentNodes().size() == 1 && art->getParentNodes().front() == art->artType);
  913. constituentsInfo.emplace_back(art, slot);
  914. attachTo(*art);
  915. }
  916. void CCombinedArtifactInstance::putAt(ArtifactLocation al)
  917. {
  918. if(al.slot == ArtifactPosition::TRANSITION_POS)
  919. {
  920. CArtifactInstance::putAt(al);
  921. }
  922. else if(ArtifactUtils::isSlotBackpack(al.slot))
  923. {
  924. CArtifactInstance::putAt(al);
  925. for(ConstituentInfo &ci : constituentsInfo)
  926. ci.slot = ArtifactPosition::PRE_FIRST;
  927. }
  928. else
  929. {
  930. CArtifactInstance *mainConstituent = figureMainConstituent(al); //it'll be replaced with combined artifact, not a lock
  931. CArtifactInstance::putAt(al); //puts combined art (this)
  932. for(ConstituentInfo & ci : constituentsInfo)
  933. {
  934. if(ci.art != mainConstituent)
  935. {
  936. const ArtifactLocation suggestedPos(al.artHolder, ci.slot);
  937. const bool inActiveSlot = vstd::isbetween(ci.slot, 0, GameConstants::BACKPACK_START);
  938. const bool suggestedPosValid = ci.art->canBePutAt(suggestedPos);
  939. if(!(inActiveSlot && suggestedPosValid)) //there is a valid suggestion where to place lock
  940. ci.slot = ArtifactUtils::getArtAnyPosition(al.getHolderArtSet(), ci.art->getTypeId());
  941. assert(ArtifactUtils::isSlotEquipment(ci.slot));
  942. al.getHolderArtSet()->setNewArtSlot(ci.slot, ci.art, true); //sets as lock
  943. }
  944. else
  945. {
  946. ci.slot = ArtifactPosition::PRE_FIRST;
  947. }
  948. }
  949. }
  950. }
  951. void CCombinedArtifactInstance::removeFrom(ArtifactLocation al)
  952. {
  953. if(ArtifactUtils::isSlotBackpack(al.slot) || al.slot == ArtifactPosition::TRANSITION_POS)
  954. {
  955. CArtifactInstance::removeFrom(al);
  956. }
  957. else
  958. {
  959. for(ConstituentInfo &ci : constituentsInfo)
  960. {
  961. if(ci.slot >= 0)
  962. {
  963. al.getHolderArtSet()->eraseArtSlot(ci.slot);
  964. ci.slot = ArtifactPosition::PRE_FIRST;
  965. }
  966. else
  967. {
  968. //main constituent
  969. CArtifactInstance::removeFrom(al);
  970. }
  971. }
  972. }
  973. }
  974. CArtifactInstance * CCombinedArtifactInstance::figureMainConstituent(const ArtifactLocation & al)
  975. {
  976. CArtifactInstance *mainConstituent = nullptr; //it'll be replaced with combined artifact, not a lock
  977. for(ConstituentInfo &ci : constituentsInfo)
  978. if(ci.slot == al.slot)
  979. mainConstituent = ci.art;
  980. if(!mainConstituent)
  981. {
  982. for(ConstituentInfo &ci : constituentsInfo)
  983. {
  984. if(vstd::contains(ci.art->artType->possibleSlots[al.getHolderArtSet()->bearerType()], al.slot))
  985. {
  986. mainConstituent = ci.art;
  987. }
  988. }
  989. }
  990. return mainConstituent;
  991. }
  992. void CCombinedArtifactInstance::deserializationFix()
  993. {
  994. for(ConstituentInfo &ci : constituentsInfo)
  995. attachTo(*ci.art);
  996. }
  997. bool CCombinedArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  998. {
  999. bool me = CArtifactInstance::isPart(supposedPart);
  1000. if(me)
  1001. return true;
  1002. //check for constituents
  1003. for(const ConstituentInfo &constituent : constituentsInfo)
  1004. if(constituent.art == supposedPart)
  1005. return true;
  1006. return false;
  1007. }
  1008. CCombinedArtifactInstance::ConstituentInfo::ConstituentInfo(CArtifactInstance * Art, const ArtifactPosition & Slot):
  1009. art(Art),
  1010. slot(Slot)
  1011. {
  1012. }
  1013. bool CCombinedArtifactInstance::ConstituentInfo::operator==(const ConstituentInfo &rhs) const
  1014. {
  1015. return art == rhs.art && slot == rhs.slot;
  1016. }
  1017. CArtifactSet::~CArtifactSet() = default;
  1018. const CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked) const
  1019. {
  1020. if(const ArtSlotInfo *si = getSlot(pos))
  1021. {
  1022. if(si->artifact && (!excludeLocked || !si->locked))
  1023. return si->artifact;
  1024. }
  1025. return nullptr;
  1026. }
  1027. CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked)
  1028. {
  1029. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  1030. }
  1031. ArtifactPosition CArtifactSet::getArtPos(const ArtifactID & aid, bool onlyWorn, bool allowLocked) const
  1032. {
  1033. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  1034. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1035. }
  1036. ArtifactPosition CArtifactSet::getArtBackpackPos(const ArtifactID & aid) const
  1037. {
  1038. const auto result = getBackpackArtPositions(aid);
  1039. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1040. }
  1041. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(const ArtifactID & aid, bool onlyWorn, bool allowLocked, bool getAll) const
  1042. {
  1043. std::vector<ArtifactPosition> result;
  1044. for(const auto & slotInfo : artifactsWorn)
  1045. if(slotInfo.second.artifact->getTypeId() == aid && (allowLocked || !slotInfo.second.locked))
  1046. result.push_back(slotInfo.first);
  1047. if(onlyWorn)
  1048. return result;
  1049. if(!getAll && !result.empty())
  1050. return result;
  1051. auto backpackPositions = getBackpackArtPositions(aid);
  1052. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  1053. return result;
  1054. }
  1055. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(const ArtifactID & aid) const
  1056. {
  1057. std::vector<ArtifactPosition> result;
  1058. si32 backpackPosition = GameConstants::BACKPACK_START;
  1059. for(const auto & artInfo : artifactsInBackpack)
  1060. {
  1061. const auto * art = artInfo.getArt();
  1062. if(art && art->artType->getId() == aid)
  1063. result.emplace_back(backpackPosition);
  1064. backpackPosition++;
  1065. }
  1066. return result;
  1067. }
  1068. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  1069. {
  1070. for(auto i : artifactsWorn)
  1071. if(i.second.artifact == art)
  1072. return i.first;
  1073. for(int i = 0; i < artifactsInBackpack.size(); i++)
  1074. if(artifactsInBackpack[i].artifact == art)
  1075. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  1076. return ArtifactPosition::PRE_FIRST;
  1077. }
  1078. const CArtifactInstance * CArtifactSet::getArtByInstanceId(const ArtifactInstanceID & artInstId) const
  1079. {
  1080. for(auto i : artifactsWorn)
  1081. if(i.second.artifact->id == artInstId)
  1082. return i.second.artifact;
  1083. for(auto i : artifactsInBackpack)
  1084. if(i.artifact->id == artInstId)
  1085. return i.artifact;
  1086. return nullptr;
  1087. }
  1088. bool CArtifactSet::hasArt(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  1089. {
  1090. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  1091. }
  1092. bool CArtifactSet::hasArtBackpack(const ArtifactID & aid) const
  1093. {
  1094. return !getBackpackArtPositions(aid).empty();
  1095. }
  1096. unsigned CArtifactSet::getArtPosCount(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  1097. {
  1098. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  1099. if(!allPositions.empty())
  1100. return allPositions.size();
  1101. if(searchBackpackAssemblies && getHiddenArt(aid))
  1102. return 1;
  1103. return 0;
  1104. }
  1105. std::pair<const CCombinedArtifactInstance *, const CArtifactInstance *> CArtifactSet::searchForConstituent(const ArtifactID & aid) const
  1106. {
  1107. for(const auto & slot : artifactsInBackpack)
  1108. {
  1109. auto art = slot.artifact;
  1110. if(art->canBeDisassembled())
  1111. {
  1112. auto * ass = dynamic_cast<CCombinedArtifactInstance *>(art.get());
  1113. for(auto& ci : ass->constituentsInfo)
  1114. {
  1115. if(ci.art->getTypeId() == aid)
  1116. {
  1117. return {ass, ci.art};
  1118. }
  1119. }
  1120. }
  1121. }
  1122. return {nullptr, nullptr};
  1123. }
  1124. const CArtifactInstance * CArtifactSet::getHiddenArt(const ArtifactID & aid) const
  1125. {
  1126. return searchForConstituent(aid).second;
  1127. }
  1128. const CCombinedArtifactInstance * CArtifactSet::getAssemblyByConstituent(const ArtifactID & aid) const
  1129. {
  1130. return searchForConstituent(aid).first;
  1131. }
  1132. const ArtSlotInfo * CArtifactSet::getSlot(const ArtifactPosition & pos) const
  1133. {
  1134. if(pos == ArtifactPosition::TRANSITION_POS)
  1135. {
  1136. // Always add to the end. Always take from the beginning.
  1137. if(artifactsTransitionPos.empty())
  1138. return nullptr;
  1139. else
  1140. return &(*artifactsTransitionPos.begin());
  1141. }
  1142. if(vstd::contains(artifactsWorn, pos))
  1143. return &artifactsWorn.at(pos);
  1144. if(pos >= ArtifactPosition::AFTER_LAST )
  1145. {
  1146. int backpackPos = (int)pos - GameConstants::BACKPACK_START;
  1147. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  1148. return nullptr;
  1149. else
  1150. return &artifactsInBackpack[backpackPos];
  1151. }
  1152. return nullptr;
  1153. }
  1154. bool CArtifactSet::isPositionFree(const ArtifactPosition & pos, bool onlyLockCheck) const
  1155. {
  1156. if(const ArtSlotInfo *s = getSlot(pos))
  1157. return (onlyLockCheck || !s->artifact) && !s->locked;
  1158. return true; //no slot means not used
  1159. }
  1160. ArtSlotInfo & CArtifactSet::retrieveNewArtSlot(const ArtifactPosition & slot)
  1161. {
  1162. assert(!vstd::contains(artifactsWorn, slot));
  1163. if(slot == ArtifactPosition::TRANSITION_POS)
  1164. {
  1165. // Always add to the end. Always take from the beginning.
  1166. artifactsTransitionPos.emplace_back();
  1167. return artifactsTransitionPos.back();
  1168. }
  1169. if(!ArtifactUtils::isSlotBackpack(slot))
  1170. return artifactsWorn[slot];
  1171. ArtSlotInfo newSlot;
  1172. size_t index = slot - GameConstants::BACKPACK_START;
  1173. auto position = artifactsInBackpack.begin() + index;
  1174. auto inserted = artifactsInBackpack.insert(position, newSlot);
  1175. return *inserted;
  1176. }
  1177. void CArtifactSet::setNewArtSlot(const ArtifactPosition & slot, CArtifactInstance * art, bool locked)
  1178. {
  1179. ArtSlotInfo & asi = retrieveNewArtSlot(slot);
  1180. asi.artifact = art;
  1181. asi.locked = locked;
  1182. }
  1183. void CArtifactSet::eraseArtSlot(const ArtifactPosition & slot)
  1184. {
  1185. if(slot == ArtifactPosition::TRANSITION_POS)
  1186. {
  1187. assert(!artifactsTransitionPos.empty());
  1188. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  1189. }
  1190. else if(ArtifactUtils::isSlotBackpack(slot))
  1191. {
  1192. auto backpackSlot = ArtifactPosition(slot - GameConstants::BACKPACK_START);
  1193. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  1194. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  1195. }
  1196. else
  1197. {
  1198. artifactsWorn.erase(slot);
  1199. }
  1200. }
  1201. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  1202. {
  1203. for(auto & elem : artifactsWorn)
  1204. if(elem.second.artifact && !elem.second.locked)
  1205. node->attachTo(*elem.second.artifact);
  1206. }
  1207. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  1208. {
  1209. //todo: creature and commander artifacts
  1210. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  1211. return;
  1212. if(!handler.saving)
  1213. {
  1214. assert(map);
  1215. artifactsInBackpack.clear();
  1216. artifactsWorn.clear();
  1217. }
  1218. auto s = handler.enterStruct(fieldName);
  1219. switch(bearerType())
  1220. {
  1221. case ArtBearer::HERO:
  1222. serializeJsonHero(handler, map);
  1223. break;
  1224. case ArtBearer::CREATURE:
  1225. serializeJsonCreature(handler, map);
  1226. break;
  1227. case ArtBearer::COMMANDER:
  1228. serializeJsonCommander(handler, map);
  1229. break;
  1230. default:
  1231. assert(false);
  1232. break;
  1233. }
  1234. }
  1235. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  1236. {
  1237. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  1238. {
  1239. serializeJsonSlot(handler, ap, map);
  1240. }
  1241. std::vector<ArtifactID> backpackTemp;
  1242. if(handler.saving)
  1243. {
  1244. backpackTemp.reserve(artifactsInBackpack.size());
  1245. for(const ArtSlotInfo & info : artifactsInBackpack)
  1246. backpackTemp.push_back(info.artifact->getTypeId());
  1247. }
  1248. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  1249. if(!handler.saving)
  1250. {
  1251. for(const ArtifactID & artifactID : backpackTemp)
  1252. {
  1253. auto * artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1254. auto slot = ArtifactPosition(GameConstants::BACKPACK_START + (si32)artifactsInBackpack.size());
  1255. if(artifact->artType->canBePutAt(this, slot))
  1256. putArtifact(slot, artifact);
  1257. }
  1258. }
  1259. }
  1260. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  1261. {
  1262. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  1263. }
  1264. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  1265. {
  1266. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  1267. }
  1268. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  1269. {
  1270. ArtifactID artifactID;
  1271. if(handler.saving)
  1272. {
  1273. const ArtSlotInfo * info = getSlot(slot);
  1274. if(info != nullptr && !info->locked)
  1275. {
  1276. artifactID = info->artifact->getTypeId();
  1277. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1278. }
  1279. }
  1280. else
  1281. {
  1282. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1283. if(artifactID != ArtifactID::NONE)
  1284. {
  1285. auto * artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1286. if(artifact->artType->canBePutAt(this, slot))
  1287. {
  1288. putArtifact(slot, artifact);
  1289. }
  1290. else
  1291. {
  1292. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  1293. }
  1294. }
  1295. }
  1296. }
  1297. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer):
  1298. Bearer(Bearer)
  1299. {
  1300. }
  1301. void CArtifactFittingSet::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  1302. {
  1303. if(art && art->canBeDisassembled() && ArtifactUtils::isSlotEquipment(pos))
  1304. {
  1305. for(auto & part : dynamic_cast<CCombinedArtifactInstance*>(art)->constituentsInfo)
  1306. {
  1307. const auto slot = ArtifactUtils::getArtAnyPosition(this, part.art->getTypeId());
  1308. assert(slot != ArtifactPosition::PRE_FIRST);
  1309. // For the ArtFittingSet is no needed to do figureMainConstituent, just lock slots
  1310. this->setNewArtSlot(slot, part.art, true);
  1311. }
  1312. }
  1313. else
  1314. {
  1315. this->setNewArtSlot(pos, art, false);
  1316. }
  1317. }
  1318. void CArtifactFittingSet::removeArtifact(ArtifactPosition pos)
  1319. {
  1320. // Removes the art from the CartifactSet, but does not remove it from art->constituentsInfo.
  1321. // removeArtifact is for CArtifactFittingSet only. Do not move it to the parent class.
  1322. auto art = getArt(pos);
  1323. if(art == nullptr)
  1324. return;
  1325. if(art->canBeDisassembled())
  1326. {
  1327. auto combinedArt = dynamic_cast<CCombinedArtifactInstance*>(art);
  1328. for(const auto & part : combinedArt->constituentsInfo)
  1329. {
  1330. if(ArtifactUtils::isSlotEquipment(part.slot))
  1331. eraseArtSlot(part.slot);
  1332. }
  1333. }
  1334. eraseArtSlot(pos);
  1335. }
  1336. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  1337. {
  1338. return this->Bearer;
  1339. }
  1340. DLL_LINKAGE ArtifactPosition ArtifactUtils::getArtAnyPosition(const CArtifactSet * target, const ArtifactID & aid)
  1341. {
  1342. const auto * art = aid.toArtifact();
  1343. for(const auto & slot : art->possibleSlots.at(target->bearerType()))
  1344. {
  1345. if(art->canBePutAt(target, slot))
  1346. return slot;
  1347. }
  1348. return getArtBackpackPosition(target, aid);
  1349. }
  1350. DLL_LINKAGE ArtifactPosition ArtifactUtils::getArtBackpackPosition(const CArtifactSet * target, const ArtifactID & aid)
  1351. {
  1352. const auto * art = aid.toArtifact();
  1353. if(art->canBePutAt(target, GameConstants::BACKPACK_START))
  1354. {
  1355. return GameConstants::BACKPACK_START;
  1356. }
  1357. return ArtifactPosition::PRE_FIRST;
  1358. }
  1359. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::unmovableSlots()
  1360. {
  1361. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1362. {
  1363. ArtifactPosition::SPELLBOOK,
  1364. ArtifactPosition::MACH4
  1365. };
  1366. return positions;
  1367. }
  1368. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::constituentWornSlots()
  1369. {
  1370. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1371. {
  1372. ArtifactPosition::HEAD,
  1373. ArtifactPosition::SHOULDERS,
  1374. ArtifactPosition::NECK,
  1375. ArtifactPosition::RIGHT_HAND,
  1376. ArtifactPosition::LEFT_HAND,
  1377. ArtifactPosition::TORSO,
  1378. ArtifactPosition::RIGHT_RING,
  1379. ArtifactPosition::LEFT_RING,
  1380. ArtifactPosition::FEET,
  1381. ArtifactPosition::MISC1,
  1382. ArtifactPosition::MISC2,
  1383. ArtifactPosition::MISC3,
  1384. ArtifactPosition::MISC4,
  1385. ArtifactPosition::MISC5,
  1386. };
  1387. return positions;
  1388. }
  1389. DLL_LINKAGE bool ArtifactUtils::isArtRemovable(const std::pair<ArtifactPosition, ArtSlotInfo> & slot)
  1390. {
  1391. return slot.second.artifact
  1392. && !slot.second.locked
  1393. && !vstd::contains(unmovableSlots(), slot.first);
  1394. }
  1395. DLL_LINKAGE bool ArtifactUtils::checkSpellbookIsNeeded(const CGHeroInstance * heroPtr, const ArtifactID & artID, const ArtifactPosition & slot)
  1396. {
  1397. // TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  1398. // Titan's Thunder creates new spellbook on equip
  1399. if(artID == ArtifactID::TITANS_THUNDER && slot == ArtifactPosition::RIGHT_HAND)
  1400. {
  1401. if(heroPtr)
  1402. {
  1403. if(heroPtr && !heroPtr->hasSpellbook())
  1404. return true;
  1405. }
  1406. }
  1407. return false;
  1408. }
  1409. DLL_LINKAGE bool ArtifactUtils::isSlotBackpack(const ArtifactPosition & slot)
  1410. {
  1411. return slot >= GameConstants::BACKPACK_START;
  1412. }
  1413. DLL_LINKAGE bool ArtifactUtils::isSlotEquipment(const ArtifactPosition & slot)
  1414. {
  1415. return slot < GameConstants::BACKPACK_START && slot >= 0;
  1416. }
  1417. DLL_LINKAGE bool ArtifactUtils::isBackpackFreeSlots(const CArtifactSet * target, const size_t reqSlots)
  1418. {
  1419. const auto backpackCap = VLC->settings()->getInteger(EGameSettings::HEROES_BACKPACK_CAP);
  1420. if(backpackCap < 0)
  1421. return true;
  1422. else
  1423. return target->artifactsInBackpack.size() + reqSlots <= backpackCap;
  1424. }
  1425. VCMI_LIB_NAMESPACE_END