CArtHandler.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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. logGlobal->warnStream() << "Warning! Artifact slot " << slotName << " not recognized!";
  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. logGlobal->warnStream() << "Warning! Artifact rarity " << className << " not recognized!";
  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. logGlobal->warnStream() << "Warning! Artifact type " << b.String() << " not recognized!";
  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. logGlobal->warnStream() << "Problem: cannot erase artifact " << art->Name() << " from list, it was not present";
  595. }
  596. else
  597. logGlobal->warnStream() << "Problem: cannot find list for artifact " << art->Name() << ", strange class. (special?)";
  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. logGlobal->warnStream() << "Warning: artifact " << artType->Name() << " doesn't have defined allowed slots for bearer of type "
  761. << artSet->bearerType();
  762. return false;
  763. }
  764. if(!vstd::contains(possibleSlots->second, slot))
  765. return false;
  766. return artSet->isPositionFree(slot, assumeDestRemoved);
  767. }
  768. void CArtifactInstance::putAt(ArtifactLocation al)
  769. {
  770. assert(canBePutAt(al));
  771. al.getHolderArtSet()->setNewArtSlot(al.slot, this, false);
  772. if(al.slot < GameConstants::BACKPACK_START)
  773. al.getHolderNode()->attachTo(this);
  774. }
  775. void CArtifactInstance::removeFrom(ArtifactLocation al)
  776. {
  777. assert(al.getHolderArtSet()->getArt(al.slot) == this);
  778. al.getHolderArtSet()->eraseArtSlot(al.slot);
  779. if(al.slot < GameConstants::BACKPACK_START)
  780. al.getHolderNode()->detachFrom(this);
  781. //TODO delete me?
  782. }
  783. bool CArtifactInstance::canBeDisassembled() const
  784. {
  785. return bool(artType->constituents);
  786. }
  787. std::vector<const CArtifact *> CArtifactInstance::assemblyPossibilities(const CArtifactSet *h) const
  788. {
  789. std::vector<const CArtifact *> ret;
  790. if(artType->constituents) //combined artifact already: no combining of combined artifacts... for now.
  791. return ret;
  792. for(const CArtifact * artifact : artType->constituentOf)
  793. {
  794. assert(artifact->constituents);
  795. bool possible = true;
  796. for(const CArtifact * constituent : *artifact->constituents) //check if all constituents are available
  797. {
  798. if(!h->hasArt(constituent->id, true)) //constituent must be equipped
  799. {
  800. possible = false;
  801. break;
  802. }
  803. }
  804. if(possible)
  805. ret.push_back(artifact);
  806. }
  807. return ret;
  808. }
  809. void CArtifactInstance::move(ArtifactLocation src, ArtifactLocation dst)
  810. {
  811. removeFrom(src);
  812. putAt(dst);
  813. }
  814. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(CArtifact *Art)
  815. {
  816. if(!Art->constituents)
  817. {
  818. auto ret = new CArtifactInstance(Art);
  819. if (dynamic_cast<CGrowingArtifact *>(Art))
  820. {
  821. auto bonus = std::make_shared<Bonus>();
  822. bonus->type = Bonus::LEVEL_COUNTER;
  823. bonus->val = 0;
  824. ret->addNewBonus (bonus);
  825. }
  826. return ret;
  827. }
  828. else
  829. {
  830. auto ret = new CCombinedArtifactInstance(Art);
  831. ret->createConstituents();
  832. return ret;
  833. }
  834. }
  835. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(int aid)
  836. {
  837. return createNewArtifactInstance(VLC->arth->artifacts[aid]);
  838. }
  839. CArtifactInstance * CArtifactInstance::createArtifact(CMap * map, int aid, int spellID)
  840. {
  841. CArtifactInstance * a = nullptr;
  842. if(aid >= 0)
  843. {
  844. if(spellID < 0)
  845. {
  846. a = CArtifactInstance::createNewArtifactInstance(aid);
  847. }
  848. else
  849. {
  850. a = CArtifactInstance::createScroll(SpellID(spellID).toSpell());
  851. }
  852. }
  853. else //FIXME: create combined artifact instance for random combined artifacts, just in case
  854. {
  855. a = new CArtifactInstance(); //random, empty
  856. }
  857. map->addNewArtifactInstance(a);
  858. //TODO make it nicer
  859. if(a->artType && (!!a->artType->constituents))
  860. {
  861. CCombinedArtifactInstance * comb = dynamic_cast<CCombinedArtifactInstance *>(a);
  862. for(CCombinedArtifactInstance::ConstituentInfo & ci : comb->constituentsInfo)
  863. {
  864. map->addNewArtifactInstance(ci.art);
  865. }
  866. }
  867. return a;
  868. }
  869. void CArtifactInstance::deserializationFix()
  870. {
  871. setType(artType);
  872. }
  873. SpellID CArtifactInstance::getGivenSpellID() const
  874. {
  875. const auto b = getBonusLocalFirst(Selector::type(Bonus::SPELL));
  876. if(!b)
  877. {
  878. logGlobal->warnStream() << "Warning: " << nodeName() << " doesn't bear any spell!";
  879. return SpellID::NONE;
  880. }
  881. return SpellID(b->subtype);
  882. }
  883. bool CArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  884. {
  885. return supposedPart == this;
  886. }
  887. bool CCombinedArtifactInstance::canBePutAt(const CArtifactSet *artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  888. {
  889. bool canMainArtifactBePlaced = CArtifactInstance::canBePutAt(artSet, slot, assumeDestRemoved);
  890. if(!canMainArtifactBePlaced)
  891. return false; //no is no...
  892. if(slot >= GameConstants::BACKPACK_START)
  893. return true; //we can always remove combined art to the backapck
  894. assert(artType->constituents);
  895. std::vector<ConstituentInfo> constituentsToBePlaced = constituentsInfo; //we'll remove constituents from that list, as we find a suitable slot for them
  896. //it may be that we picked a combined artifact in hero screen (though technically it's still there) to move it
  897. //so we remove from the list all constituents that are already present on dst hero in the form of locks
  898. for(const ConstituentInfo &constituent : constituentsInfo)
  899. {
  900. if(constituent.art == artSet->getArt(constituent.slot, false)) //no need to worry about locked constituent
  901. constituentsToBePlaced -= constituent;
  902. }
  903. //we iterate over all active slots and check if constituents fits them
  904. for (int i = 0; i < GameConstants::BACKPACK_START; i++)
  905. {
  906. for(auto art = constituentsToBePlaced.begin(); art != constituentsToBePlaced.end(); art++)
  907. {
  908. 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
  909. {
  910. constituentsToBePlaced.erase(art);
  911. break;
  912. }
  913. }
  914. }
  915. return constituentsToBePlaced.empty();
  916. }
  917. bool CCombinedArtifactInstance::canBeDisassembled() const
  918. {
  919. return true;
  920. }
  921. CCombinedArtifactInstance::CCombinedArtifactInstance(CArtifact *Art)
  922. : CArtifactInstance(Art) //TODO: seems unued, but need to be written
  923. {
  924. }
  925. CCombinedArtifactInstance::CCombinedArtifactInstance()
  926. {
  927. }
  928. void CCombinedArtifactInstance::createConstituents()
  929. {
  930. assert(artType);
  931. assert(artType->constituents);
  932. for(const CArtifact * art : *artType->constituents)
  933. {
  934. addAsConstituent(CArtifactInstance::createNewArtifactInstance(art->id), ArtifactPosition::PRE_FIRST);
  935. }
  936. }
  937. void CCombinedArtifactInstance::addAsConstituent(CArtifactInstance *art, ArtifactPosition slot)
  938. {
  939. assert(vstd::contains(*artType->constituents, art->artType.get()));
  940. assert(art->getParentNodes().size() == 1 && art->getParentNodes().front() == art->artType);
  941. constituentsInfo.push_back(ConstituentInfo(art, slot));
  942. attachTo(art);
  943. }
  944. void CCombinedArtifactInstance::putAt(ArtifactLocation al)
  945. {
  946. if(al.slot >= GameConstants::BACKPACK_START)
  947. {
  948. CArtifactInstance::putAt(al);
  949. for(ConstituentInfo &ci : constituentsInfo)
  950. ci.slot = ArtifactPosition::PRE_FIRST;
  951. }
  952. else
  953. {
  954. CArtifactInstance *mainConstituent = figureMainConstituent(al); //it'll be replaced with combined artifact, not a lock
  955. CArtifactInstance::putAt(al); //puts combined art (this)
  956. for(ConstituentInfo &ci : constituentsInfo)
  957. {
  958. if(ci.art != mainConstituent)
  959. {
  960. const ArtifactLocation suggestedPos(al.artHolder, ci.slot);
  961. const bool inActiveSlot = vstd::isbetween(ci.slot, 0, GameConstants::BACKPACK_START);
  962. const bool suggestedPosValid = ci.art->canBePutAt(suggestedPos);
  963. ArtifactPosition pos = ArtifactPosition::PRE_FIRST;
  964. if(inActiveSlot && suggestedPosValid) //there is a valid suggestion where to place lock
  965. pos = ci.slot;
  966. else
  967. ci.slot = pos = ci.art->firstAvailableSlot(al.getHolderArtSet());
  968. assert(pos < GameConstants::BACKPACK_START);
  969. al.getHolderArtSet()->setNewArtSlot(pos, ci.art, true); //sets as lock
  970. }
  971. else
  972. {
  973. ci.slot = ArtifactPosition::PRE_FIRST;
  974. }
  975. }
  976. }
  977. }
  978. void CCombinedArtifactInstance::removeFrom(ArtifactLocation al)
  979. {
  980. if(al.slot >= GameConstants::BACKPACK_START)
  981. {
  982. CArtifactInstance::removeFrom(al);
  983. }
  984. else
  985. {
  986. for(ConstituentInfo &ci : constituentsInfo)
  987. {
  988. if(ci.slot >= 0)
  989. {
  990. al.getHolderArtSet()->eraseArtSlot(ci.slot);
  991. ci.slot = ArtifactPosition::PRE_FIRST;
  992. }
  993. else
  994. {
  995. //main constituent
  996. CArtifactInstance::removeFrom(al);
  997. }
  998. }
  999. }
  1000. }
  1001. CArtifactInstance * CCombinedArtifactInstance::figureMainConstituent(const ArtifactLocation al)
  1002. {
  1003. CArtifactInstance *mainConstituent = nullptr; //it'll be replaced with combined artifact, not a lock
  1004. for(ConstituentInfo &ci : constituentsInfo)
  1005. if(ci.slot == al.slot)
  1006. mainConstituent = ci.art;
  1007. if(!mainConstituent)
  1008. {
  1009. for(ConstituentInfo &ci : constituentsInfo)
  1010. {
  1011. if(vstd::contains(ci.art->artType->possibleSlots[al.getHolderArtSet()->bearerType()], al.slot))
  1012. {
  1013. mainConstituent = ci.art;
  1014. }
  1015. }
  1016. }
  1017. return mainConstituent;
  1018. }
  1019. void CCombinedArtifactInstance::deserializationFix()
  1020. {
  1021. for(ConstituentInfo &ci : constituentsInfo)
  1022. attachTo(ci.art);
  1023. }
  1024. bool CCombinedArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  1025. {
  1026. bool me = CArtifactInstance::isPart(supposedPart);
  1027. if(me)
  1028. return true;
  1029. //check for constituents
  1030. for(const ConstituentInfo &constituent : constituentsInfo)
  1031. if(constituent.art == supposedPart)
  1032. return true;
  1033. return false;
  1034. }
  1035. CCombinedArtifactInstance::ConstituentInfo::ConstituentInfo(CArtifactInstance *Art, ArtifactPosition Slot)
  1036. {
  1037. art = Art;
  1038. slot = Slot;
  1039. }
  1040. bool CCombinedArtifactInstance::ConstituentInfo::operator==(const ConstituentInfo &rhs) const
  1041. {
  1042. return art == rhs.art && slot == rhs.slot;
  1043. }
  1044. CArtifactSet::~CArtifactSet() = default;
  1045. const CArtifactInstance* CArtifactSet::getArt(ArtifactPosition pos, bool excludeLocked) const
  1046. {
  1047. if(const ArtSlotInfo *si = getSlot(pos))
  1048. {
  1049. if(si->artifact && (!excludeLocked || !si->locked))
  1050. return si->artifact;
  1051. }
  1052. return nullptr;
  1053. }
  1054. CArtifactInstance* CArtifactSet::getArt(ArtifactPosition pos, bool excludeLocked)
  1055. {
  1056. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  1057. }
  1058. ArtifactPosition CArtifactSet::getArtPos(int aid, bool onlyWorn) const
  1059. {
  1060. for(auto i = artifactsWorn.cbegin(); i != artifactsWorn.cend(); i++)
  1061. if(i->second.artifact->artType->id == aid)
  1062. return i->first;
  1063. if(onlyWorn)
  1064. return ArtifactPosition::PRE_FIRST;
  1065. for(int i = 0; i < artifactsInBackpack.size(); i++)
  1066. if(artifactsInBackpack[i].artifact->artType->id == aid)
  1067. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  1068. return ArtifactPosition::PRE_FIRST;
  1069. }
  1070. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  1071. {
  1072. for(auto i : artifactsWorn)
  1073. if(i.second.artifact == art)
  1074. return i.first;
  1075. for(int i = 0; i < artifactsInBackpack.size(); i++)
  1076. if(artifactsInBackpack[i].artifact == art)
  1077. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  1078. return ArtifactPosition::PRE_FIRST;
  1079. }
  1080. const CArtifactInstance * CArtifactSet::getArtByInstanceId( ArtifactInstanceID artInstId ) const
  1081. {
  1082. for(auto i : artifactsWorn)
  1083. if(i.second.artifact->id == artInstId)
  1084. return i.second.artifact;
  1085. for(auto i : artifactsInBackpack)
  1086. if(i.artifact->id == artInstId)
  1087. return i.artifact;
  1088. return nullptr;
  1089. }
  1090. bool CArtifactSet::hasArt(ui32 aid, bool onlyWorn,
  1091. bool searchBackpackAssemblies) const
  1092. {
  1093. return getArtPos(aid, onlyWorn) != ArtifactPosition::PRE_FIRST ||
  1094. (searchBackpackAssemblies && getHiddenArt(aid));
  1095. }
  1096. std::pair<const CCombinedArtifactInstance *, const CArtifactInstance *>
  1097. CArtifactSet::searchForConstituent(int aid) const
  1098. {
  1099. for(auto & slot : artifactsInBackpack)
  1100. {
  1101. auto art = slot.artifact;
  1102. if(art->canBeDisassembled())
  1103. {
  1104. auto ass = static_cast<CCombinedArtifactInstance *>(art.get());
  1105. for(auto& ci : ass->constituentsInfo)
  1106. {
  1107. if(ci.art->artType->id == aid)
  1108. {
  1109. return {ass, ci.art};
  1110. }
  1111. }
  1112. }
  1113. }
  1114. return {nullptr, nullptr};
  1115. }
  1116. const CArtifactInstance *CArtifactSet::getHiddenArt(int aid) const
  1117. {
  1118. return searchForConstituent(aid).second;
  1119. }
  1120. const CCombinedArtifactInstance *CArtifactSet::getAssemblyByConstituent(int aid) const
  1121. {
  1122. return searchForConstituent(aid).first;
  1123. }
  1124. const ArtSlotInfo * CArtifactSet::getSlot(ArtifactPosition pos) const
  1125. {
  1126. if(vstd::contains(artifactsWorn, pos))
  1127. return &artifactsWorn.at(pos);
  1128. if(pos >= ArtifactPosition::AFTER_LAST )
  1129. {
  1130. int backpackPos = (int)pos - GameConstants::BACKPACK_START;
  1131. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  1132. return nullptr;
  1133. else
  1134. return &artifactsInBackpack[backpackPos];
  1135. }
  1136. return nullptr;
  1137. }
  1138. bool CArtifactSet::isPositionFree(ArtifactPosition pos, bool onlyLockCheck) const
  1139. {
  1140. if(const ArtSlotInfo *s = getSlot(pos))
  1141. return (onlyLockCheck || !s->artifact) && !s->locked;
  1142. return true; //no slot means not used
  1143. }
  1144. ArtSlotInfo & CArtifactSet::retreiveNewArtSlot(ArtifactPosition slot)
  1145. {
  1146. assert(!vstd::contains(artifactsWorn, slot));
  1147. ArtSlotInfo &ret = slot < GameConstants::BACKPACK_START
  1148. ? artifactsWorn[slot]
  1149. : *artifactsInBackpack.insert(artifactsInBackpack.begin() + (slot - GameConstants::BACKPACK_START), ArtSlotInfo());
  1150. return ret;
  1151. }
  1152. void CArtifactSet::setNewArtSlot(ArtifactPosition slot, CArtifactInstance *art, bool locked)
  1153. {
  1154. ArtSlotInfo &asi = retreiveNewArtSlot(slot);
  1155. asi.artifact = art;
  1156. asi.locked = locked;
  1157. }
  1158. void CArtifactSet::eraseArtSlot(ArtifactPosition slot)
  1159. {
  1160. if(slot < GameConstants::BACKPACK_START)
  1161. {
  1162. artifactsWorn.erase(slot);
  1163. }
  1164. else
  1165. {
  1166. slot = ArtifactPosition(slot - GameConstants::BACKPACK_START);
  1167. artifactsInBackpack.erase(artifactsInBackpack.begin() + slot);
  1168. }
  1169. }
  1170. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  1171. {
  1172. for(auto & elem : artifactsWorn)
  1173. if(elem.second.artifact && !elem.second.locked)
  1174. node->attachTo(elem.second.artifact);
  1175. }
  1176. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  1177. {
  1178. //todo: creature and commander artifacts
  1179. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  1180. return;
  1181. if(!handler.saving)
  1182. {
  1183. assert(map);
  1184. artifactsInBackpack.clear();
  1185. artifactsWorn.clear();
  1186. }
  1187. auto s = handler.enterStruct(fieldName);
  1188. switch(bearerType())
  1189. {
  1190. case ArtBearer::HERO:
  1191. serializeJsonHero(handler, map);
  1192. break;
  1193. case ArtBearer::CREATURE:
  1194. serializeJsonCreature(handler, map);
  1195. break;
  1196. case ArtBearer::COMMANDER:
  1197. serializeJsonCommander(handler, map);
  1198. break;
  1199. default:
  1200. assert(false);
  1201. break;
  1202. }
  1203. }
  1204. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  1205. {
  1206. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  1207. {
  1208. serializeJsonSlot(handler, ap, map);
  1209. }
  1210. std::vector<ArtifactID> backpackTemp;
  1211. if(handler.saving)
  1212. {
  1213. backpackTemp.reserve(artifactsInBackpack.size());
  1214. for(const ArtSlotInfo & info : artifactsInBackpack)
  1215. backpackTemp.push_back(info.artifact->artType->id);
  1216. }
  1217. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp, &CArtHandler::decodeArfifact, &CArtHandler::encodeArtifact);
  1218. if(!handler.saving)
  1219. {
  1220. for(const ArtifactID & artifactID : backpackTemp)
  1221. {
  1222. auto artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1223. auto slot = ArtifactPosition(GameConstants::BACKPACK_START + artifactsInBackpack.size());
  1224. if(artifact->canBePutAt(this, slot))
  1225. putArtifact(slot, artifact);
  1226. }
  1227. }
  1228. }
  1229. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  1230. {
  1231. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  1232. }
  1233. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  1234. {
  1235. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  1236. }
  1237. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  1238. {
  1239. ArtifactID artifactID;
  1240. if(handler.saving)
  1241. {
  1242. const ArtSlotInfo * info = getSlot(slot);
  1243. if(info != nullptr && !info->locked)
  1244. {
  1245. artifactID = info->artifact->artType->id;
  1246. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE, &CArtHandler::decodeArfifact, &CArtHandler::encodeArtifact);
  1247. }
  1248. }
  1249. else
  1250. {
  1251. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE, &CArtHandler::decodeArfifact, &CArtHandler::encodeArtifact);
  1252. if(artifactID != ArtifactID::NONE)
  1253. {
  1254. auto artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1255. if(artifact->canBePutAt(this, slot))
  1256. {
  1257. putArtifact(slot, artifact);
  1258. }
  1259. else
  1260. {
  1261. logGlobal->debugStream() << "Artifact can't be put at the specified location."; //TODO add more debugging information
  1262. }
  1263. }
  1264. }
  1265. }