CArtHandler.cpp 42 KB

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