CArtHandler.cpp 45 KB

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