CArtHandler.cpp 46 KB

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