CArtHandler.cpp 46 KB

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