CArtHandler.cpp 41 KB

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