CArtHandler.cpp 46 KB

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