CArtHandler.cpp 45 KB

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