CArtHandler.cpp 45 KB

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