CArtHandler.cpp 45 KB

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