CArtHandler.cpp 39 KB

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