CArtHandler.cpp 45 KB

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