CArtHandler.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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(!(art->aClass & CArtifact::ART_SPECIAL))
  633. {
  634. auto & artifactList = treasures;
  635. switch(art->aClass)
  636. {
  637. case CArtifact::ART_MINOR:
  638. artifactList = minors;
  639. break;
  640. case CArtifact::ART_MAJOR:
  641. artifactList = majors;
  642. break;
  643. case CArtifact::ART_RELIC:
  644. artifactList = relics;
  645. break;
  646. }
  647. if(artifactList.empty())
  648. fillList(artifactList, art->aClass);
  649. auto itr = vstd::find(artifactList, art);
  650. if(itr != artifactList.end())
  651. {
  652. artifactList.erase(itr);
  653. }
  654. else
  655. logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
  656. }
  657. else
  658. logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
  659. }
  660. void CArtHandler::fillList( std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass )
  661. {
  662. assert(listToBeFilled.empty());
  663. for (auto & elem : allowedArtifacts)
  664. {
  665. if (elem->aClass == artifactClass)
  666. listToBeFilled.push_back(elem);
  667. }
  668. }
  669. void CArtHandler::afterLoadFinalization()
  670. {
  671. //All artifacts have their id, so we can properly update their bonuses' source ids.
  672. for(auto &art : objects)
  673. {
  674. for(auto &bonus : art->getExportedBonusList())
  675. {
  676. assert(art == objects[art->id]);
  677. assert(bonus->source == Bonus::ARTIFACT);
  678. bonus->sid = art->id;
  679. }
  680. }
  681. CBonusSystemNode::treeHasChanged();
  682. }
  683. CArtifactInstance::CArtifactInstance()
  684. {
  685. init();
  686. }
  687. CArtifactInstance::CArtifactInstance( CArtifact *Art)
  688. {
  689. init();
  690. setType(Art);
  691. }
  692. void CArtifactInstance::setType( CArtifact *Art )
  693. {
  694. artType = Art;
  695. attachTo(*Art);
  696. }
  697. std::string CArtifactInstance::nodeName() const
  698. {
  699. return "Artifact instance of " + (artType ? artType->getJsonKey() : std::string("uninitialized")) + " type";
  700. }
  701. CArtifactInstance * CArtifactInstance::createScroll(const SpellID & sid)
  702. {
  703. auto * ret = new CArtifactInstance(VLC->arth->objects[ArtifactID::SPELL_SCROLL]);
  704. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::SPELL, Bonus::ARTIFACT_INSTANCE, -1, ArtifactID::SPELL_SCROLL, sid);
  705. ret->addNewBonus(b);
  706. return ret;
  707. }
  708. void CArtifactInstance::init()
  709. {
  710. id = ArtifactInstanceID();
  711. id = static_cast<ArtifactInstanceID>(ArtifactID::NONE); //to be randomized
  712. setNodeType(ARTIFACT_INSTANCE);
  713. }
  714. std::string CArtifactInstance::getEffectiveDescription(const CGHeroInstance * hero) const
  715. {
  716. std::string text = artType->getDescriptionTranslated();
  717. if (!vstd::contains(text, '{'))
  718. text = '{' + artType->getNameTranslated() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style
  719. if(artType->getId() == ArtifactID::SPELL_SCROLL)
  720. {
  721. // 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.
  722. // so we want to replace text in [...] with a spell name
  723. // however other language versions don't have name placeholder at all, so we have to be careful
  724. SpellID spellID = getGivenSpellID();
  725. size_t nameStart = text.find_first_of('[');
  726. size_t nameEnd = text.find_first_of(']', nameStart);
  727. if(spellID.getNum() >= 0)
  728. {
  729. if(nameStart != std::string::npos && nameEnd != std::string::npos)
  730. text = text.replace(nameStart, nameEnd - nameStart + 1, spellID.toSpell(VLC->spells())->getNameTranslated());
  731. }
  732. }
  733. else if(hero && !artType->constituentOf.empty()) //display info about set
  734. {
  735. std::string artList;
  736. auto * combinedArt = artType->constituentOf[0];
  737. text += "\n\n";
  738. text += "{" + combinedArt->getNameTranslated() + "}";
  739. int wornArtifacts = 0;
  740. for(auto * a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set?
  741. {
  742. artList += "\n" + a->getNameTranslated();
  743. if (hero->hasArt(a->getId(), true))
  744. wornArtifacts++;
  745. }
  746. text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " +
  747. boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList;
  748. //TODO: fancy colors and fonts for this text
  749. }
  750. return text;
  751. }
  752. ArtifactID CArtifactInstance::getTypeId() const
  753. {
  754. return artType->getId();
  755. }
  756. bool CArtifactInstance::canBePutAt(const ArtifactLocation & al, bool assumeDestRemoved) const
  757. {
  758. return artType->canBePutAt(al.getHolderArtSet(), al.slot, assumeDestRemoved);
  759. }
  760. void CArtifactInstance::putAt(ArtifactLocation al)
  761. {
  762. assert(canBePutAt(al));
  763. al.getHolderArtSet()->setNewArtSlot(al.slot, this, false);
  764. if(ArtifactUtils::isSlotEquipment(al.slot))
  765. al.getHolderNode()->attachTo(*this);
  766. }
  767. void CArtifactInstance::removeFrom(ArtifactLocation al)
  768. {
  769. assert(al.getHolderArtSet()->getArt(al.slot) == this);
  770. al.getHolderArtSet()->eraseArtSlot(al.slot);
  771. if(ArtifactUtils::isSlotEquipment(al.slot))
  772. al.getHolderNode()->detachFrom(*this);
  773. }
  774. bool CArtifactInstance::canBeDisassembled() const
  775. {
  776. return artType->canBeDisassembled();
  777. }
  778. std::vector<const CArtifact *> CArtifactInstance::assemblyPossibilities(const CArtifactSet * h, bool equipped) const
  779. {
  780. std::vector<const CArtifact *> ret;
  781. if(artType->constituents) //combined artifact already: no combining of combined artifacts... for now.
  782. return ret;
  783. for(const auto * artifact : artType->constituentOf)
  784. {
  785. assert(artifact->constituents);
  786. bool possible = true;
  787. for(const auto * constituent : *artifact->constituents) //check if all constituents are available
  788. {
  789. if(equipped)
  790. {
  791. // Search for equipped arts
  792. if (!h->hasArt(constituent->getId(), true, false, false))
  793. {
  794. possible = false;
  795. break;
  796. }
  797. }
  798. else
  799. {
  800. // Search in backpack
  801. if(!h->hasArtBackpack(constituent->getId()))
  802. {
  803. possible = false;
  804. break;
  805. }
  806. }
  807. }
  808. if(possible)
  809. ret.push_back(artifact);
  810. }
  811. return ret;
  812. }
  813. void CArtifactInstance::move(const ArtifactLocation & src, const ArtifactLocation & dst)
  814. {
  815. removeFrom(src);
  816. putAt(dst);
  817. }
  818. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(CArtifact *Art)
  819. {
  820. if(!Art->constituents)
  821. {
  822. auto * ret = new CArtifactInstance(Art);
  823. if (dynamic_cast<CGrowingArtifact *>(Art))
  824. {
  825. auto bonus = std::make_shared<Bonus>();
  826. bonus->type = Bonus::LEVEL_COUNTER;
  827. bonus->val = 0;
  828. ret->addNewBonus (bonus);
  829. }
  830. return ret;
  831. }
  832. else
  833. {
  834. auto * ret = new CCombinedArtifactInstance(Art);
  835. ret->createConstituents();
  836. return ret;
  837. }
  838. }
  839. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(const ArtifactID & aid)
  840. {
  841. return createNewArtifactInstance(VLC->arth->objects[aid]);
  842. }
  843. CArtifactInstance * CArtifactInstance::createArtifact(CMap * map, const ArtifactID & aid, int spellID)
  844. {
  845. CArtifactInstance * a = nullptr;
  846. if(aid >= 0)
  847. {
  848. if(spellID < 0)
  849. {
  850. a = CArtifactInstance::createNewArtifactInstance(aid);
  851. }
  852. else
  853. {
  854. a = CArtifactInstance::createScroll(SpellID(spellID));
  855. }
  856. }
  857. else //FIXME: create combined artifact instance for random combined artifacts, just in case
  858. {
  859. a = new CArtifactInstance(); //random, empty
  860. }
  861. map->addNewArtifactInstance(a);
  862. //TODO make it nicer
  863. if(a->artType && (!!a->artType->constituents))
  864. {
  865. auto * comb = dynamic_cast<CCombinedArtifactInstance *>(a);
  866. for(CCombinedArtifactInstance::ConstituentInfo & ci : comb->constituentsInfo)
  867. {
  868. map->addNewArtifactInstance(ci.art);
  869. }
  870. }
  871. return a;
  872. }
  873. void CArtifactInstance::deserializationFix()
  874. {
  875. setType(artType);
  876. }
  877. SpellID CArtifactInstance::getGivenSpellID() const
  878. {
  879. const auto b = getBonusLocalFirst(Selector::type()(Bonus::SPELL));
  880. if(!b)
  881. {
  882. logMod->warn("Warning: %s doesn't bear any spell!", nodeName());
  883. return SpellID::NONE;
  884. }
  885. return SpellID(b->subtype);
  886. }
  887. bool CArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  888. {
  889. return supposedPart == this;
  890. }
  891. CCombinedArtifactInstance::CCombinedArtifactInstance(CArtifact *Art)
  892. : CArtifactInstance(Art) //TODO: seems unused, but need to be written
  893. {
  894. }
  895. void CCombinedArtifactInstance::createConstituents()
  896. {
  897. assert(artType);
  898. assert(artType->constituents);
  899. for(const CArtifact * art : *artType->constituents)
  900. {
  901. addAsConstituent(CArtifactInstance::createNewArtifactInstance(art->getId()), ArtifactPosition::PRE_FIRST);
  902. }
  903. }
  904. void CCombinedArtifactInstance::addAsConstituent(CArtifactInstance * art, const ArtifactPosition & slot)
  905. {
  906. assert(vstd::contains_if(*artType->constituents, [=](const CArtifact * constituent){
  907. return constituent->getId() == art->artType->getId();
  908. }));
  909. assert(art->getParentNodes().size() == 1 && art->getParentNodes().front() == art->artType);
  910. constituentsInfo.emplace_back(art, slot);
  911. attachTo(*art);
  912. }
  913. void CCombinedArtifactInstance::putAt(ArtifactLocation al)
  914. {
  915. if(al.slot == ArtifactPosition::TRANSITION_POS)
  916. {
  917. CArtifactInstance::putAt(al);
  918. }
  919. else if(ArtifactUtils::isSlotBackpack(al.slot))
  920. {
  921. CArtifactInstance::putAt(al);
  922. for(ConstituentInfo &ci : constituentsInfo)
  923. ci.slot = ArtifactPosition::PRE_FIRST;
  924. }
  925. else
  926. {
  927. CArtifactInstance *mainConstituent = figureMainConstituent(al); //it'll be replaced with combined artifact, not a lock
  928. CArtifactInstance::putAt(al); //puts combined art (this)
  929. for(ConstituentInfo & ci : constituentsInfo)
  930. {
  931. if(ci.art != mainConstituent)
  932. {
  933. const ArtifactLocation suggestedPos(al.artHolder, ci.slot);
  934. const bool inActiveSlot = vstd::isbetween(ci.slot, 0, GameConstants::BACKPACK_START);
  935. const bool suggestedPosValid = ci.art->canBePutAt(suggestedPos);
  936. if(!(inActiveSlot && suggestedPosValid)) //there is a valid suggestion where to place lock
  937. ci.slot = ArtifactUtils::getArtAnyPosition(al.getHolderArtSet(), ci.art->getTypeId());
  938. assert(ArtifactUtils::isSlotEquipment(ci.slot));
  939. al.getHolderArtSet()->setNewArtSlot(ci.slot, ci.art, true); //sets as lock
  940. }
  941. else
  942. {
  943. ci.slot = ArtifactPosition::PRE_FIRST;
  944. }
  945. }
  946. }
  947. }
  948. void CCombinedArtifactInstance::removeFrom(ArtifactLocation al)
  949. {
  950. if(ArtifactUtils::isSlotBackpack(al.slot) || al.slot == ArtifactPosition::TRANSITION_POS)
  951. {
  952. CArtifactInstance::removeFrom(al);
  953. }
  954. else
  955. {
  956. for(ConstituentInfo &ci : constituentsInfo)
  957. {
  958. if(ci.slot >= 0)
  959. {
  960. al.getHolderArtSet()->eraseArtSlot(ci.slot);
  961. ci.slot = ArtifactPosition::PRE_FIRST;
  962. }
  963. else
  964. {
  965. //main constituent
  966. CArtifactInstance::removeFrom(al);
  967. }
  968. }
  969. }
  970. }
  971. CArtifactInstance * CCombinedArtifactInstance::figureMainConstituent(const ArtifactLocation & al)
  972. {
  973. CArtifactInstance *mainConstituent = nullptr; //it'll be replaced with combined artifact, not a lock
  974. for(ConstituentInfo &ci : constituentsInfo)
  975. if(ci.slot == al.slot)
  976. mainConstituent = ci.art;
  977. if(!mainConstituent)
  978. {
  979. for(ConstituentInfo &ci : constituentsInfo)
  980. {
  981. if(vstd::contains(ci.art->artType->possibleSlots[al.getHolderArtSet()->bearerType()], al.slot))
  982. {
  983. mainConstituent = ci.art;
  984. }
  985. }
  986. }
  987. return mainConstituent;
  988. }
  989. void CCombinedArtifactInstance::deserializationFix()
  990. {
  991. for(ConstituentInfo &ci : constituentsInfo)
  992. attachTo(*ci.art);
  993. }
  994. bool CCombinedArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  995. {
  996. bool me = CArtifactInstance::isPart(supposedPart);
  997. if(me)
  998. return true;
  999. //check for constituents
  1000. for(const ConstituentInfo &constituent : constituentsInfo)
  1001. if(constituent.art == supposedPart)
  1002. return true;
  1003. return false;
  1004. }
  1005. CCombinedArtifactInstance::ConstituentInfo::ConstituentInfo(CArtifactInstance * Art, const ArtifactPosition & Slot):
  1006. art(Art),
  1007. slot(Slot)
  1008. {
  1009. }
  1010. bool CCombinedArtifactInstance::ConstituentInfo::operator==(const ConstituentInfo &rhs) const
  1011. {
  1012. return art == rhs.art && slot == rhs.slot;
  1013. }
  1014. CArtifactSet::~CArtifactSet() = default;
  1015. const CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked) const
  1016. {
  1017. if(const ArtSlotInfo *si = getSlot(pos))
  1018. {
  1019. if(si->artifact && (!excludeLocked || !si->locked))
  1020. return si->artifact;
  1021. }
  1022. return nullptr;
  1023. }
  1024. CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked)
  1025. {
  1026. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  1027. }
  1028. ArtifactPosition CArtifactSet::getArtPos(const ArtifactID & aid, bool onlyWorn, bool allowLocked) const
  1029. {
  1030. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  1031. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1032. }
  1033. ArtifactPosition CArtifactSet::getArtBackpackPos(const ArtifactID & aid) const
  1034. {
  1035. const auto result = getBackpackArtPositions(aid);
  1036. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1037. }
  1038. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(const ArtifactID & aid, bool onlyWorn, bool allowLocked, bool getAll) const
  1039. {
  1040. std::vector<ArtifactPosition> result;
  1041. for(const auto & slotInfo : artifactsWorn)
  1042. if(slotInfo.second.artifact->getTypeId() == aid && (allowLocked || !slotInfo.second.locked))
  1043. result.push_back(slotInfo.first);
  1044. if(onlyWorn)
  1045. return result;
  1046. if(!getAll && !result.empty())
  1047. return result;
  1048. auto backpackPositions = getBackpackArtPositions(aid);
  1049. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  1050. return result;
  1051. }
  1052. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(const ArtifactID & aid) const
  1053. {
  1054. std::vector<ArtifactPosition> result;
  1055. si32 backpackPosition = GameConstants::BACKPACK_START;
  1056. for(const auto & artInfo : artifactsInBackpack)
  1057. {
  1058. const auto * art = artInfo.getArt();
  1059. if(art && art->artType->getId() == aid)
  1060. result.emplace_back(backpackPosition);
  1061. backpackPosition++;
  1062. }
  1063. return result;
  1064. }
  1065. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  1066. {
  1067. for(auto i : artifactsWorn)
  1068. if(i.second.artifact == art)
  1069. return i.first;
  1070. for(int i = 0; i < artifactsInBackpack.size(); i++)
  1071. if(artifactsInBackpack[i].artifact == art)
  1072. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  1073. return ArtifactPosition::PRE_FIRST;
  1074. }
  1075. const CArtifactInstance * CArtifactSet::getArtByInstanceId(const ArtifactInstanceID & artInstId) const
  1076. {
  1077. for(auto i : artifactsWorn)
  1078. if(i.second.artifact->id == artInstId)
  1079. return i.second.artifact;
  1080. for(auto i : artifactsInBackpack)
  1081. if(i.artifact->id == artInstId)
  1082. return i.artifact;
  1083. return nullptr;
  1084. }
  1085. bool CArtifactSet::hasArt(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  1086. {
  1087. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  1088. }
  1089. bool CArtifactSet::hasArtBackpack(const ArtifactID & aid) const
  1090. {
  1091. return !getBackpackArtPositions(aid).empty();
  1092. }
  1093. unsigned CArtifactSet::getArtPosCount(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  1094. {
  1095. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  1096. if(!allPositions.empty())
  1097. return allPositions.size();
  1098. if(searchBackpackAssemblies && getHiddenArt(aid))
  1099. return 1;
  1100. return 0;
  1101. }
  1102. std::pair<const CCombinedArtifactInstance *, const CArtifactInstance *> CArtifactSet::searchForConstituent(const ArtifactID & aid) const
  1103. {
  1104. for(const auto & slot : artifactsInBackpack)
  1105. {
  1106. auto art = slot.artifact;
  1107. if(art->canBeDisassembled())
  1108. {
  1109. auto * ass = dynamic_cast<CCombinedArtifactInstance *>(art.get());
  1110. for(auto& ci : ass->constituentsInfo)
  1111. {
  1112. if(ci.art->getTypeId() == aid)
  1113. {
  1114. return {ass, ci.art};
  1115. }
  1116. }
  1117. }
  1118. }
  1119. return {nullptr, nullptr};
  1120. }
  1121. const CArtifactInstance * CArtifactSet::getHiddenArt(const ArtifactID & aid) const
  1122. {
  1123. return searchForConstituent(aid).second;
  1124. }
  1125. const CCombinedArtifactInstance * CArtifactSet::getAssemblyByConstituent(const ArtifactID & aid) const
  1126. {
  1127. return searchForConstituent(aid).first;
  1128. }
  1129. const ArtSlotInfo * CArtifactSet::getSlot(const ArtifactPosition & pos) const
  1130. {
  1131. if(pos == ArtifactPosition::TRANSITION_POS)
  1132. {
  1133. // Always add to the end. Always take from the beginning.
  1134. if(artifactsTransitionPos.empty())
  1135. return nullptr;
  1136. else
  1137. return &(*artifactsTransitionPos.begin());
  1138. }
  1139. if(vstd::contains(artifactsWorn, pos))
  1140. return &artifactsWorn.at(pos);
  1141. if(pos >= ArtifactPosition::AFTER_LAST )
  1142. {
  1143. int backpackPos = (int)pos - GameConstants::BACKPACK_START;
  1144. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  1145. return nullptr;
  1146. else
  1147. return &artifactsInBackpack[backpackPos];
  1148. }
  1149. return nullptr;
  1150. }
  1151. bool CArtifactSet::isPositionFree(const ArtifactPosition & pos, bool onlyLockCheck) const
  1152. {
  1153. if(const ArtSlotInfo *s = getSlot(pos))
  1154. return (onlyLockCheck || !s->artifact) && !s->locked;
  1155. return true; //no slot means not used
  1156. }
  1157. ArtSlotInfo & CArtifactSet::retrieveNewArtSlot(const ArtifactPosition & slot)
  1158. {
  1159. assert(!vstd::contains(artifactsWorn, slot));
  1160. if(slot == ArtifactPosition::TRANSITION_POS)
  1161. {
  1162. // Always add to the end. Always take from the beginning.
  1163. artifactsTransitionPos.emplace_back();
  1164. return artifactsTransitionPos.back();
  1165. }
  1166. if(!ArtifactUtils::isSlotBackpack(slot))
  1167. return artifactsWorn[slot];
  1168. ArtSlotInfo newSlot;
  1169. size_t index = slot - GameConstants::BACKPACK_START;
  1170. auto position = artifactsInBackpack.begin() + index;
  1171. auto inserted = artifactsInBackpack.insert(position, newSlot);
  1172. return *inserted;
  1173. }
  1174. void CArtifactSet::setNewArtSlot(const ArtifactPosition & slot, CArtifactInstance * art, bool locked)
  1175. {
  1176. ArtSlotInfo & asi = retrieveNewArtSlot(slot);
  1177. asi.artifact = art;
  1178. asi.locked = locked;
  1179. }
  1180. void CArtifactSet::eraseArtSlot(const ArtifactPosition & slot)
  1181. {
  1182. if(slot == ArtifactPosition::TRANSITION_POS)
  1183. {
  1184. assert(!artifactsTransitionPos.empty());
  1185. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  1186. }
  1187. else if(ArtifactUtils::isSlotBackpack(slot))
  1188. {
  1189. auto backpackSlot = ArtifactPosition(slot - GameConstants::BACKPACK_START);
  1190. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  1191. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  1192. }
  1193. else
  1194. {
  1195. artifactsWorn.erase(slot);
  1196. }
  1197. }
  1198. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  1199. {
  1200. for(auto & elem : artifactsWorn)
  1201. if(elem.second.artifact && !elem.second.locked)
  1202. node->attachTo(*elem.second.artifact);
  1203. }
  1204. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  1205. {
  1206. //todo: creature and commander artifacts
  1207. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  1208. return;
  1209. if(!handler.saving)
  1210. {
  1211. assert(map);
  1212. artifactsInBackpack.clear();
  1213. artifactsWorn.clear();
  1214. }
  1215. auto s = handler.enterStruct(fieldName);
  1216. switch(bearerType())
  1217. {
  1218. case ArtBearer::HERO:
  1219. serializeJsonHero(handler, map);
  1220. break;
  1221. case ArtBearer::CREATURE:
  1222. serializeJsonCreature(handler, map);
  1223. break;
  1224. case ArtBearer::COMMANDER:
  1225. serializeJsonCommander(handler, map);
  1226. break;
  1227. default:
  1228. assert(false);
  1229. break;
  1230. }
  1231. }
  1232. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  1233. {
  1234. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  1235. {
  1236. serializeJsonSlot(handler, ap, map);
  1237. }
  1238. std::vector<ArtifactID> backpackTemp;
  1239. if(handler.saving)
  1240. {
  1241. backpackTemp.reserve(artifactsInBackpack.size());
  1242. for(const ArtSlotInfo & info : artifactsInBackpack)
  1243. backpackTemp.push_back(info.artifact->getTypeId());
  1244. }
  1245. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  1246. if(!handler.saving)
  1247. {
  1248. for(const ArtifactID & artifactID : backpackTemp)
  1249. {
  1250. auto * artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1251. auto slot = ArtifactPosition(GameConstants::BACKPACK_START + (si32)artifactsInBackpack.size());
  1252. if(artifact->artType->canBePutAt(this, slot))
  1253. putArtifact(slot, artifact);
  1254. }
  1255. }
  1256. }
  1257. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  1258. {
  1259. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  1260. }
  1261. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  1262. {
  1263. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  1264. }
  1265. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  1266. {
  1267. ArtifactID artifactID;
  1268. if(handler.saving)
  1269. {
  1270. const ArtSlotInfo * info = getSlot(slot);
  1271. if(info != nullptr && !info->locked)
  1272. {
  1273. artifactID = info->artifact->getTypeId();
  1274. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1275. }
  1276. }
  1277. else
  1278. {
  1279. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1280. if(artifactID != ArtifactID::NONE)
  1281. {
  1282. auto * artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1283. if(artifact->artType->canBePutAt(this, slot))
  1284. {
  1285. putArtifact(slot, artifact);
  1286. }
  1287. else
  1288. {
  1289. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  1290. }
  1291. }
  1292. }
  1293. }
  1294. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer):
  1295. Bearer(Bearer)
  1296. {
  1297. }
  1298. void CArtifactFittingSet::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  1299. {
  1300. if(art && art->canBeDisassembled() && ArtifactUtils::isSlotEquipment(pos))
  1301. {
  1302. for(auto & part : dynamic_cast<CCombinedArtifactInstance*>(art)->constituentsInfo)
  1303. {
  1304. const auto slot = ArtifactUtils::getArtAnyPosition(this, part.art->getTypeId());
  1305. assert(slot != ArtifactPosition::PRE_FIRST);
  1306. // For the ArtFittingSet is no needed to do figureMainConstituent, just lock slots
  1307. this->setNewArtSlot(slot, part.art, true);
  1308. }
  1309. }
  1310. else
  1311. {
  1312. this->setNewArtSlot(pos, art, false);
  1313. }
  1314. }
  1315. void CArtifactFittingSet::removeArtifact(ArtifactPosition pos)
  1316. {
  1317. // Removes the art from the CartifactSet, but does not remove it from art->constituentsInfo.
  1318. // removeArtifact is for CArtifactFittingSet only. Do not move it to the parent class.
  1319. auto art = getArt(pos);
  1320. if(art == nullptr)
  1321. return;
  1322. if(art->canBeDisassembled())
  1323. {
  1324. auto combinedArt = dynamic_cast<CCombinedArtifactInstance*>(art);
  1325. for(const auto & part : combinedArt->constituentsInfo)
  1326. {
  1327. if(ArtifactUtils::isSlotEquipment(part.slot))
  1328. eraseArtSlot(part.slot);
  1329. }
  1330. }
  1331. eraseArtSlot(pos);
  1332. }
  1333. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  1334. {
  1335. return this->Bearer;
  1336. }
  1337. DLL_LINKAGE ArtifactPosition ArtifactUtils::getArtAnyPosition(const CArtifactSet * target, const ArtifactID & aid)
  1338. {
  1339. const auto * art = aid.toArtifact();
  1340. for(const auto & slot : art->possibleSlots.at(target->bearerType()))
  1341. {
  1342. if(art->canBePutAt(target, slot))
  1343. return slot;
  1344. }
  1345. return getArtBackpackPosition(target, aid);
  1346. }
  1347. DLL_LINKAGE ArtifactPosition ArtifactUtils::getArtBackpackPosition(const CArtifactSet * target, const ArtifactID & aid)
  1348. {
  1349. const auto * art = aid.toArtifact();
  1350. if(art->canBePutAt(target, GameConstants::BACKPACK_START))
  1351. {
  1352. return GameConstants::BACKPACK_START;
  1353. }
  1354. return ArtifactPosition::PRE_FIRST;
  1355. }
  1356. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::unmovableSlots()
  1357. {
  1358. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1359. {
  1360. ArtifactPosition::SPELLBOOK,
  1361. ArtifactPosition::MACH4
  1362. };
  1363. return positions;
  1364. }
  1365. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::constituentWornSlots()
  1366. {
  1367. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1368. {
  1369. ArtifactPosition::HEAD,
  1370. ArtifactPosition::SHOULDERS,
  1371. ArtifactPosition::NECK,
  1372. ArtifactPosition::RIGHT_HAND,
  1373. ArtifactPosition::LEFT_HAND,
  1374. ArtifactPosition::TORSO,
  1375. ArtifactPosition::RIGHT_RING,
  1376. ArtifactPosition::LEFT_RING,
  1377. ArtifactPosition::FEET,
  1378. ArtifactPosition::MISC1,
  1379. ArtifactPosition::MISC2,
  1380. ArtifactPosition::MISC3,
  1381. ArtifactPosition::MISC4,
  1382. ArtifactPosition::MISC5,
  1383. };
  1384. return positions;
  1385. }
  1386. DLL_LINKAGE bool ArtifactUtils::isArtRemovable(const std::pair<ArtifactPosition, ArtSlotInfo> & slot)
  1387. {
  1388. return slot.second.artifact
  1389. && !slot.second.locked
  1390. && !vstd::contains(unmovableSlots(), slot.first);
  1391. }
  1392. DLL_LINKAGE bool ArtifactUtils::checkSpellbookIsNeeded(const CGHeroInstance * heroPtr, const ArtifactID & artID, const ArtifactPosition & slot)
  1393. {
  1394. // TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  1395. // Titan's Thunder creates new spellbook on equip
  1396. if(artID == ArtifactID::TITANS_THUNDER && slot == ArtifactPosition::RIGHT_HAND)
  1397. {
  1398. if(heroPtr)
  1399. {
  1400. if(heroPtr && !heroPtr->hasSpellbook())
  1401. return true;
  1402. }
  1403. }
  1404. return false;
  1405. }
  1406. DLL_LINKAGE bool ArtifactUtils::isSlotBackpack(const ArtifactPosition & slot)
  1407. {
  1408. return slot >= GameConstants::BACKPACK_START;
  1409. }
  1410. DLL_LINKAGE bool ArtifactUtils::isSlotEquipment(const ArtifactPosition & slot)
  1411. {
  1412. return slot < GameConstants::BACKPACK_START && slot >= 0;
  1413. }
  1414. DLL_LINKAGE bool ArtifactUtils::isBackpackFreeSlots(const CArtifactSet * target, const size_t reqSlots)
  1415. {
  1416. const auto backpackCap = VLC->settings()->getInteger(EGameSettings::HEROES_BACKPACK_CAP);
  1417. if(backpackCap < 0)
  1418. return true;
  1419. else
  1420. return target->artifactsInBackpack.size() + reqSlots <= backpackCap;
  1421. }
  1422. VCMI_LIB_NAMESPACE_END