CArtHandler.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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 "ArtifactUtils.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "GameSettings.h"
  15. #include "mapObjects/MapObjects.h"
  16. #include "StringConstants.h"
  17. #include "mapObjectConstructors/AObjectTypeHandler.h"
  18. #include "mapObjectConstructors/CObjectClassesHandler.h"
  19. #include "serializer/JsonSerializeFormat.h"
  20. // Note: list must match entries in ArtTraits.txt
  21. #define ART_POS_LIST \
  22. ART_POS(SPELLBOOK) \
  23. ART_POS(MACH4) \
  24. ART_POS(MACH3) \
  25. ART_POS(MACH2) \
  26. ART_POS(MACH1) \
  27. ART_POS(MISC5) \
  28. ART_POS(MISC4) \
  29. ART_POS(MISC3) \
  30. ART_POS(MISC2) \
  31. ART_POS(MISC1) \
  32. ART_POS(FEET) \
  33. ART_POS(LEFT_RING) \
  34. ART_POS(RIGHT_RING) \
  35. ART_POS(TORSO) \
  36. ART_POS(LEFT_HAND) \
  37. ART_POS(RIGHT_HAND) \
  38. ART_POS(NECK) \
  39. ART_POS(SHOULDERS) \
  40. ART_POS(HEAD)
  41. VCMI_LIB_NAMESPACE_BEGIN
  42. bool CCombinedArtifact::isCombined() const
  43. {
  44. return !(constituents.empty());
  45. }
  46. const std::vector<CArtifact*> & CCombinedArtifact::getConstituents() const
  47. {
  48. return constituents;
  49. }
  50. const std::vector<CArtifact*> & CCombinedArtifact::getPartOf() const
  51. {
  52. return partOf;
  53. }
  54. bool CScrollArtifact::isScroll() const
  55. {
  56. return static_cast<const CArtifact*>(this)->getId() == ArtifactID::SPELL_SCROLL;
  57. }
  58. bool CGrowingArtifact::isGrowing() const
  59. {
  60. return !bonusesPerLevel.empty() || !thresholdBonuses.empty();
  61. }
  62. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel()
  63. {
  64. return bonusesPerLevel;
  65. }
  66. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel() const
  67. {
  68. return bonusesPerLevel;
  69. }
  70. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses()
  71. {
  72. return thresholdBonuses;
  73. }
  74. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses() const
  75. {
  76. return thresholdBonuses;
  77. }
  78. int32_t CArtifact::getIndex() const
  79. {
  80. return id.toEnum();
  81. }
  82. int32_t CArtifact::getIconIndex() const
  83. {
  84. return iconIndex;
  85. }
  86. std::string CArtifact::getJsonKey() const
  87. {
  88. return modScope + ':' + identifier;
  89. }
  90. void CArtifact::registerIcons(const IconRegistar & cb) const
  91. {
  92. cb(getIconIndex(), 0, "ARTIFACT", image);
  93. cb(getIconIndex(), 0, "ARTIFACTLARGE", large);
  94. }
  95. ArtifactID CArtifact::getId() const
  96. {
  97. return id;
  98. }
  99. const IBonusBearer * CArtifact::getBonusBearer() const
  100. {
  101. return this;
  102. }
  103. std::string CArtifact::getDescriptionTranslated() const
  104. {
  105. return VLC->generaltexth->translate(getDescriptionTextID());
  106. }
  107. std::string CArtifact::getEventTranslated() const
  108. {
  109. return VLC->generaltexth->translate(getEventTextID());
  110. }
  111. std::string CArtifact::getNameTranslated() const
  112. {
  113. return VLC->generaltexth->translate(getNameTextID());
  114. }
  115. std::string CArtifact::getDescriptionTextID() const
  116. {
  117. return TextIdentifier("artifact", modScope, identifier, "description").get();
  118. }
  119. std::string CArtifact::getEventTextID() const
  120. {
  121. return TextIdentifier("artifact", modScope, identifier, "event").get();
  122. }
  123. std::string CArtifact::getNameTextID() const
  124. {
  125. return TextIdentifier("artifact", modScope, identifier, "name").get();
  126. }
  127. uint32_t CArtifact::getPrice() const
  128. {
  129. return price;
  130. }
  131. CreatureID CArtifact::getWarMachine() const
  132. {
  133. return warMachine;
  134. }
  135. bool CArtifact::isBig() const
  136. {
  137. return warMachine != CreatureID::NONE;
  138. }
  139. bool CArtifact::isTradable() const
  140. {
  141. switch(id)
  142. {
  143. case ArtifactID::SPELLBOOK:
  144. case ArtifactID::GRAIL:
  145. return false;
  146. default:
  147. return !isBig();
  148. }
  149. }
  150. bool CArtifact::canBePutAt(const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  151. {
  152. auto simpleArtCanBePutAt = [this](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  153. {
  154. if(ArtifactUtils::isSlotBackpack(slot))
  155. {
  156. if(isBig() || !ArtifactUtils::isBackpackFreeSlots(artSet))
  157. return false;
  158. return true;
  159. }
  160. if(!vstd::contains(possibleSlots.at(artSet->bearerType()), slot))
  161. return false;
  162. return artSet->isPositionFree(slot, assumeDestRemoved);
  163. };
  164. auto artCanBePutAt = [this, simpleArtCanBePutAt](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  165. {
  166. if(isCombined())
  167. {
  168. if(!simpleArtCanBePutAt(artSet, slot, assumeDestRemoved))
  169. return false;
  170. if(ArtifactUtils::isSlotBackpack(slot))
  171. return true;
  172. CArtifactFittingSet fittingSet(artSet->bearerType());
  173. fittingSet.artifactsWorn = artSet->artifactsWorn;
  174. if(assumeDestRemoved)
  175. fittingSet.removeArtifact(slot);
  176. for(const auto art : constituents)
  177. {
  178. auto possibleSlot = ArtifactUtils::getArtAnyPosition(&fittingSet, art->getId());
  179. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  180. {
  181. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  182. }
  183. else
  184. {
  185. return false;
  186. }
  187. }
  188. return true;
  189. }
  190. else
  191. {
  192. return simpleArtCanBePutAt(artSet, slot, assumeDestRemoved);
  193. }
  194. };
  195. if(slot == ArtifactPosition::TRANSITION_POS)
  196. return true;
  197. if(slot == ArtifactPosition::FIRST_AVAILABLE)
  198. {
  199. for(const auto & slot : possibleSlots.at(artSet->bearerType()))
  200. {
  201. if(artCanBePutAt(artSet, slot, assumeDestRemoved))
  202. return true;
  203. }
  204. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  205. }
  206. else if(ArtifactUtils::isSlotBackpack(slot))
  207. {
  208. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  209. }
  210. else
  211. {
  212. return artCanBePutAt(artSet, slot, assumeDestRemoved);
  213. }
  214. }
  215. CArtifact::CArtifact()
  216. : iconIndex(ArtifactID::NONE),
  217. price(0)
  218. {
  219. setNodeType(ARTIFACT);
  220. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  221. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  222. possibleSlots[ArtBearer::COMMANDER];
  223. }
  224. //This destructor should be placed here to avoid side effects
  225. CArtifact::~CArtifact() = default;
  226. int CArtifact::getArtClassSerial() const
  227. {
  228. if(id == ArtifactID::SPELL_SCROLL)
  229. return 4;
  230. switch(aClass)
  231. {
  232. case ART_TREASURE:
  233. return 0;
  234. case ART_MINOR:
  235. return 1;
  236. case ART_MAJOR:
  237. return 2;
  238. case ART_RELIC:
  239. return 3;
  240. case ART_SPECIAL:
  241. return 5;
  242. }
  243. return -1;
  244. }
  245. std::string CArtifact::nodeName() const
  246. {
  247. return "Artifact: " + getNameTranslated();
  248. }
  249. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  250. {
  251. b->source = BonusSource::ARTIFACT;
  252. b->duration = BonusDuration::PERMANENT;
  253. b->description = getNameTranslated();
  254. CBonusSystemNode::addNewBonus(b);
  255. }
  256. const std::map<ArtBearer::ArtBearer, std::vector<ArtifactPosition>> & CArtifact::getPossibleSlots() const
  257. {
  258. return possibleSlots;
  259. }
  260. void CArtifact::updateFrom(const JsonNode& data)
  261. {
  262. //TODO:CArtifact::updateFrom
  263. }
  264. void CArtifact::setImage(int32_t iconIndex, std::string image, std::string large)
  265. {
  266. this->iconIndex = iconIndex;
  267. this->image = image;
  268. this->large = large;
  269. }
  270. CArtHandler::~CArtHandler() = default;
  271. std::vector<JsonNode> CArtHandler::loadLegacyData()
  272. {
  273. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_ARTIFACT);
  274. objects.resize(dataSize);
  275. std::vector<JsonNode> h3Data;
  276. h3Data.reserve(dataSize);
  277. #define ART_POS(x) #x ,
  278. const std::vector<std::string> artSlots = { ART_POS_LIST };
  279. #undef ART_POS
  280. static std::map<char, std::string> classes =
  281. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  282. CLegacyConfigParser parser("DATA/ARTRAITS.TXT");
  283. CLegacyConfigParser events("DATA/ARTEVENT.TXT");
  284. parser.endLine(); // header
  285. parser.endLine();
  286. for (size_t i = 0; i < dataSize; i++)
  287. {
  288. JsonNode artData;
  289. artData["text"]["name"].String() = parser.readString();
  290. artData["text"]["event"].String() = events.readString();
  291. artData["value"].Float() = parser.readNumber();
  292. for(const auto & artSlot : artSlots)
  293. {
  294. if(parser.readString() == "x")
  295. {
  296. artData["slot"].Vector().push_back(JsonNode());
  297. artData["slot"].Vector().back().String() = artSlot;
  298. }
  299. }
  300. artData["class"].String() = classes[parser.readString()[0]];
  301. artData["text"]["description"].String() = parser.readString();
  302. parser.endLine();
  303. events.endLine();
  304. h3Data.push_back(artData);
  305. }
  306. return h3Data;
  307. }
  308. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  309. {
  310. auto * object = loadFromJson(scope, data, name, objects.size());
  311. object->iconIndex = object->getIndex() + 5;
  312. objects.emplace_back(object);
  313. registerObject(scope, "artifact", name, object->id);
  314. }
  315. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  316. {
  317. auto * object = loadFromJson(scope, data, name, index);
  318. object->iconIndex = object->getIndex();
  319. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  320. objects[index] = object;
  321. registerObject(scope, "artifact", name, object->id);
  322. }
  323. const std::vector<std::string> & CArtHandler::getTypeNames() const
  324. {
  325. static const std::vector<std::string> typeNames = { "artifact" };
  326. return typeNames;
  327. }
  328. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  329. {
  330. assert(identifier.find(':') == std::string::npos);
  331. assert(!scope.empty());
  332. CArtifact * art = new CArtifact();
  333. if(!node["growing"].isNull())
  334. {
  335. for(auto bonus : node["growing"]["bonusesPerLevel"].Vector())
  336. {
  337. art->bonusesPerLevel.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  338. JsonUtils::parseBonus(bonus["bonus"], &art->bonusesPerLevel.back().second);
  339. }
  340. for(auto bonus : node["growing"]["thresholdBonuses"].Vector())
  341. {
  342. art->thresholdBonuses.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  343. JsonUtils::parseBonus(bonus["bonus"], &art->thresholdBonuses.back().second);
  344. }
  345. }
  346. art->id = ArtifactID(index);
  347. art->identifier = identifier;
  348. art->modScope = scope;
  349. const JsonNode & text = node["text"];
  350. VLC->generaltexth->registerString(scope, art->getNameTextID(), text["name"].String());
  351. VLC->generaltexth->registerString(scope, art->getDescriptionTextID(), text["description"].String());
  352. VLC->generaltexth->registerString(scope, art->getEventTextID(), text["event"].String());
  353. const JsonNode & graphics = node["graphics"];
  354. art->image = graphics["image"].String();
  355. if(!graphics["large"].isNull())
  356. art->large = graphics["large"].String();
  357. else
  358. art->large = art->image;
  359. art->advMapDef = graphics["map"].String();
  360. art->price = static_cast<ui32>(node["value"].Float());
  361. art->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  362. loadSlots(art, node);
  363. loadClass(art, node);
  364. loadType(art, node);
  365. loadComponents(art, node);
  366. for(const auto & b : node["bonuses"].Vector())
  367. {
  368. auto bonus = JsonUtils::parseBonus(b);
  369. art->addNewBonus(bonus);
  370. }
  371. const JsonNode & warMachine = node["warMachine"];
  372. if(warMachine.getType() == JsonNode::JsonType::DATA_STRING && !warMachine.String().empty())
  373. {
  374. VLC->identifiers()->requestIdentifier("creature", warMachine, [=](si32 id)
  375. {
  376. art->warMachine = CreatureID(id);
  377. //this assumes that creature object is stored before registration
  378. VLC->creh->objects.at(id)->warMachine = art->id;
  379. });
  380. }
  381. VLC->identifiers()->requestIdentifier(scope, "object", "artifact", [=](si32 index)
  382. {
  383. JsonNode conf;
  384. conf.setMeta(scope);
  385. VLC->objtypeh->loadSubObject(art->identifier, conf, Obj::ARTIFACT, art->getIndex());
  386. if(!art->advMapDef.empty())
  387. {
  388. JsonNode templ;
  389. templ["animation"].String() = art->advMapDef;
  390. templ.setMeta(scope);
  391. // add new template.
  392. // Necessary for objects added via mods that don't have any templates in H3
  393. VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->addTemplate(templ);
  394. }
  395. // object does not have any templates - this is not usable object (e.g. pseudo-art like lock)
  396. if(VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->getTemplates().empty())
  397. VLC->objtypeh->removeSubObject(Obj::ARTIFACT, art->getIndex());
  398. });
  399. return art;
  400. }
  401. ArtifactPosition::ArtifactPosition(std::string slotName):
  402. num(ArtifactPosition::PRE_FIRST)
  403. {
  404. #define ART_POS(x) { #x, ArtifactPosition::x },
  405. static const std::map<std::string, ArtifactPosition> artifactPositionMap = { ART_POS_LIST };
  406. #undef ART_POS
  407. auto it = artifactPositionMap.find (slotName);
  408. if (it != artifactPositionMap.end())
  409. num = it->second;
  410. else
  411. logMod->warn("Warning! Artifact slot %s not recognized!", slotName);
  412. }
  413. void CArtHandler::addSlot(CArtifact * art, const std::string & slotID) const
  414. {
  415. static const std::vector<ArtifactPosition> miscSlots =
  416. {
  417. ArtifactPosition::MISC1, ArtifactPosition::MISC2, ArtifactPosition::MISC3, ArtifactPosition::MISC4, ArtifactPosition::MISC5
  418. };
  419. static const std::vector<ArtifactPosition> ringSlots =
  420. {
  421. ArtifactPosition::RIGHT_RING, ArtifactPosition::LEFT_RING
  422. };
  423. if (slotID == "MISC")
  424. {
  425. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], miscSlots);
  426. }
  427. else if (slotID == "RING")
  428. {
  429. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], ringSlots);
  430. }
  431. else
  432. {
  433. auto slot = ArtifactPosition(slotID);
  434. if (slot != ArtifactPosition::PRE_FIRST)
  435. art->possibleSlots[ArtBearer::HERO].push_back(slot);
  436. }
  437. }
  438. void CArtHandler::loadSlots(CArtifact * art, const JsonNode & node) const
  439. {
  440. if (!node["slot"].isNull()) //we assume non-hero slots are irrelevant?
  441. {
  442. if (node["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  443. addSlot(art, node["slot"].String());
  444. else
  445. {
  446. for (const JsonNode & slot : node["slot"].Vector())
  447. addSlot(art, slot.String());
  448. }
  449. std::sort(art->possibleSlots.at(ArtBearer::HERO).begin(), art->possibleSlots.at(ArtBearer::HERO).end());
  450. }
  451. }
  452. CArtifact::EartClass CArtHandler::stringToClass(const std::string & className)
  453. {
  454. static const std::map<std::string, CArtifact::EartClass> artifactClassMap =
  455. {
  456. {"TREASURE", CArtifact::ART_TREASURE},
  457. {"MINOR", CArtifact::ART_MINOR},
  458. {"MAJOR", CArtifact::ART_MAJOR},
  459. {"RELIC", CArtifact::ART_RELIC},
  460. {"SPECIAL", CArtifact::ART_SPECIAL}
  461. };
  462. auto it = artifactClassMap.find (className);
  463. if (it != artifactClassMap.end())
  464. return it->second;
  465. logMod->warn("Warning! Artifact rarity %s not recognized!", className);
  466. return CArtifact::ART_SPECIAL;
  467. }
  468. void CArtHandler::loadClass(CArtifact * art, const JsonNode & node) const
  469. {
  470. art->aClass = stringToClass(node["class"].String());
  471. }
  472. void CArtHandler::loadType(CArtifact * art, const JsonNode & node) const
  473. {
  474. #define ART_BEARER(x) { #x, ArtBearer::x },
  475. static const std::map<std::string, int> artifactBearerMap = { ART_BEARER_LIST };
  476. #undef ART_BEARER
  477. for (const JsonNode & b : node["type"].Vector())
  478. {
  479. auto it = artifactBearerMap.find (b.String());
  480. if (it != artifactBearerMap.end())
  481. {
  482. int bearerType = it->second;
  483. switch (bearerType)
  484. {
  485. case ArtBearer::HERO://TODO: allow arts having several possible bearers
  486. break;
  487. case ArtBearer::COMMANDER:
  488. makeItCommanderArt (art); //original artifacts should have only one bearer type
  489. break;
  490. case ArtBearer::CREATURE:
  491. makeItCreatureArt (art);
  492. break;
  493. }
  494. }
  495. else
  496. logMod->warn("Warning! Artifact type %s not recognized!", b.String());
  497. }
  498. }
  499. void CArtHandler::loadComponents(CArtifact * art, const JsonNode & node)
  500. {
  501. if (!node["components"].isNull())
  502. {
  503. for(const auto & component : node["components"].Vector())
  504. {
  505. VLC->identifiers()->requestIdentifier("artifact", component, [=](si32 id)
  506. {
  507. // when this code is called both combinational art as well as component are loaded
  508. // so it is safe to access any of them
  509. art->constituents.push_back(objects[id]);
  510. objects[id]->partOf.push_back(art);
  511. });
  512. }
  513. }
  514. }
  515. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags, std::function<bool(ArtifactID)> accepts)
  516. {
  517. auto getAllowedArts = [&](std::vector<ConstTransitivePtr<CArtifact> > &out, std::vector<CArtifact*> *arts, CArtifact::EartClass flag)
  518. {
  519. if (arts->empty()) //restock available arts
  520. fillList(*arts, flag);
  521. for (auto & arts_i : *arts)
  522. {
  523. if (accepts(arts_i->id))
  524. {
  525. CArtifact *art = arts_i;
  526. out.emplace_back(art);
  527. }
  528. }
  529. };
  530. auto getAllowed = [&](std::vector<ConstTransitivePtr<CArtifact> > &out)
  531. {
  532. if (flags & CArtifact::ART_TREASURE)
  533. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  534. if (flags & CArtifact::ART_MINOR)
  535. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  536. if (flags & CArtifact::ART_MAJOR)
  537. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  538. if (flags & CArtifact::ART_RELIC)
  539. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  540. if(out.empty()) //no artifact of specified rarity, we need to take another one
  541. {
  542. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  543. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  544. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  545. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  546. }
  547. if(out.empty()) //no arts are available at all
  548. {
  549. out.resize (64);
  550. std::fill_n (out.begin(), 64, objects[2]); //Give Grail - this can't be banned (hopefully)
  551. }
  552. };
  553. std::vector<ConstTransitivePtr<CArtifact> > out;
  554. getAllowed(out);
  555. ArtifactID artID = (*RandomGeneratorUtil::nextItem(out, rand))->id;
  556. erasePickedArt(artID);
  557. return artID;
  558. }
  559. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::function<bool(ArtifactID)> accepts)
  560. {
  561. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  562. }
  563. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags)
  564. {
  565. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  566. }
  567. void CArtHandler::makeItCreatureArt(CArtifact * a, bool onlyCreature)
  568. {
  569. if (onlyCreature)
  570. {
  571. a->possibleSlots[ArtBearer::HERO].clear();
  572. a->possibleSlots[ArtBearer::COMMANDER].clear();
  573. }
  574. a->possibleSlots[ArtBearer::CREATURE].push_back(ArtifactPosition::CREATURE_SLOT);
  575. }
  576. void CArtHandler::makeItCommanderArt(CArtifact * a, bool onlyCommander)
  577. {
  578. if (onlyCommander)
  579. {
  580. a->possibleSlots[ArtBearer::HERO].clear();
  581. a->possibleSlots[ArtBearer::CREATURE].clear();
  582. }
  583. for (int i = ArtifactPosition::COMMANDER1; i <= ArtifactPosition::COMMANDER6; ++i)
  584. a->possibleSlots[ArtBearer::COMMANDER].push_back(ArtifactPosition(i));
  585. }
  586. bool CArtHandler::legalArtifact(const ArtifactID & id)
  587. {
  588. auto art = objects[id];
  589. //assert ( (!art->constituents) || art->constituents->size() ); //artifacts is not combined or has some components
  590. if(art->isCombined())
  591. return false; //no combo artifacts spawning
  592. if(art->aClass < CArtifact::ART_TREASURE || art->aClass > CArtifact::ART_RELIC)
  593. return false; // invalid class
  594. if(!art->possibleSlots[ArtBearer::HERO].empty())
  595. return true;
  596. if(!art->possibleSlots[ArtBearer::CREATURE].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_ARTIFACT))
  597. return true;
  598. if(!art->possibleSlots[ArtBearer::COMMANDER].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS))
  599. return true;
  600. return false;
  601. }
  602. void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
  603. {
  604. allowedArtifacts.clear();
  605. treasures.clear();
  606. minors.clear();
  607. majors.clear();
  608. relics.clear();
  609. for (ArtifactID i=ArtifactID::SPELLBOOK; i < ArtifactID(static_cast<si32>(objects.size())); i.advance(1))
  610. {
  611. if (allowed[i] && legalArtifact(ArtifactID(i)))
  612. allowedArtifacts.push_back(objects[i]);
  613. //keep im mind that artifact can be worn by more than one type of bearer
  614. }
  615. }
  616. std::vector<bool> CArtHandler::getDefaultAllowed() const
  617. {
  618. std::vector<bool> allowedArtifacts;
  619. allowedArtifacts.resize(127, true);
  620. allowedArtifacts.resize(141, false);
  621. allowedArtifacts.resize(size(), true);
  622. return allowedArtifacts;
  623. }
  624. void CArtHandler::erasePickedArt(const ArtifactID & id)
  625. {
  626. CArtifact *art = objects[id];
  627. std::vector<CArtifact*> * artifactList = nullptr;
  628. switch(art->aClass)
  629. {
  630. case CArtifact::ART_TREASURE:
  631. artifactList = &treasures;
  632. break;
  633. case CArtifact::ART_MINOR:
  634. artifactList = &minors;
  635. break;
  636. case CArtifact::ART_MAJOR:
  637. artifactList = &majors;
  638. break;
  639. case CArtifact::ART_RELIC:
  640. artifactList = &relics;
  641. break;
  642. default:
  643. logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
  644. return;
  645. }
  646. if(artifactList->empty())
  647. fillList(*artifactList, art->aClass);
  648. auto itr = vstd::find(*artifactList, art);
  649. if(itr != artifactList->end())
  650. {
  651. artifactList->erase(itr);
  652. }
  653. else
  654. logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
  655. }
  656. void CArtHandler::fillList( std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass )
  657. {
  658. assert(listToBeFilled.empty());
  659. for (auto & elem : allowedArtifacts)
  660. {
  661. if (elem->aClass == artifactClass)
  662. listToBeFilled.push_back(elem);
  663. }
  664. }
  665. void CArtHandler::afterLoadFinalization()
  666. {
  667. //All artifacts have their id, so we can properly update their bonuses' source ids.
  668. for(auto &art : objects)
  669. {
  670. for(auto &bonus : art->getExportedBonusList())
  671. {
  672. assert(art == objects[art->id]);
  673. assert(bonus->source == BonusSource::ARTIFACT);
  674. bonus->sid = art->id;
  675. }
  676. }
  677. CBonusSystemNode::treeHasChanged();
  678. }
  679. CArtifactSet::~CArtifactSet() = default;
  680. const CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked) const
  681. {
  682. if(const ArtSlotInfo * si = getSlot(pos))
  683. {
  684. if(si->artifact && (!excludeLocked || !si->locked))
  685. return si->artifact;
  686. }
  687. return nullptr;
  688. }
  689. CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked)
  690. {
  691. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  692. }
  693. ArtifactPosition CArtifactSet::getArtPos(const ArtifactID & aid, bool onlyWorn, bool allowLocked) const
  694. {
  695. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  696. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  697. }
  698. ArtifactPosition CArtifactSet::getArtBackpackPos(const ArtifactID & aid) const
  699. {
  700. const auto result = getBackpackArtPositions(aid);
  701. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  702. }
  703. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(const ArtifactID & aid, bool onlyWorn, bool allowLocked, bool getAll) const
  704. {
  705. std::vector<ArtifactPosition> result;
  706. for(const auto & slotInfo : artifactsWorn)
  707. if(slotInfo.second.artifact->getTypeId() == aid && (allowLocked || !slotInfo.second.locked))
  708. result.push_back(slotInfo.first);
  709. if(onlyWorn)
  710. return result;
  711. if(!getAll && !result.empty())
  712. return result;
  713. auto backpackPositions = getBackpackArtPositions(aid);
  714. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  715. return result;
  716. }
  717. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(const ArtifactID & aid) const
  718. {
  719. std::vector<ArtifactPosition> result;
  720. si32 backpackPosition = GameConstants::BACKPACK_START;
  721. for(const auto & artInfo : artifactsInBackpack)
  722. {
  723. const auto * art = artInfo.getArt();
  724. if(art && art->artType->getId() == aid)
  725. result.emplace_back(backpackPosition);
  726. backpackPosition++;
  727. }
  728. return result;
  729. }
  730. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  731. {
  732. for(auto i : artifactsWorn)
  733. if(i.second.artifact == art)
  734. return i.first;
  735. for(int i = 0; i < artifactsInBackpack.size(); i++)
  736. if(artifactsInBackpack[i].artifact == art)
  737. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  738. return ArtifactPosition::PRE_FIRST;
  739. }
  740. const CArtifactInstance * CArtifactSet::getArtByInstanceId(const ArtifactInstanceID & artInstId) const
  741. {
  742. for(auto i : artifactsWorn)
  743. if(i.second.artifact->getId() == artInstId)
  744. return i.second.artifact;
  745. for(auto i : artifactsInBackpack)
  746. if(i.artifact->getId() == artInstId)
  747. return i.artifact;
  748. return nullptr;
  749. }
  750. const ArtifactPosition CArtifactSet::getSlotByInstance(const CArtifactInstance * artInst) const
  751. {
  752. if(artInst)
  753. {
  754. for(const auto & slot : artInst->artType->getPossibleSlots().at(bearerType()))
  755. if(getArt(slot) == artInst)
  756. return slot;
  757. auto backpackSlot = GameConstants::BACKPACK_START;
  758. for(auto & slotInfo : artifactsInBackpack)
  759. {
  760. if(slotInfo.getArt() == artInst)
  761. return backpackSlot;
  762. backpackSlot = ArtifactPosition(backpackSlot + 1);
  763. }
  764. }
  765. return ArtifactPosition::PRE_FIRST;
  766. }
  767. bool CArtifactSet::hasArt(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  768. {
  769. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  770. }
  771. bool CArtifactSet::hasArtBackpack(const ArtifactID & aid) const
  772. {
  773. return !getBackpackArtPositions(aid).empty();
  774. }
  775. unsigned CArtifactSet::getArtPosCount(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  776. {
  777. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  778. if(!allPositions.empty())
  779. return allPositions.size();
  780. if(searchBackpackAssemblies && getHiddenArt(aid))
  781. return 1;
  782. return 0;
  783. }
  784. void CArtifactSet::putArtifact(ArtifactPosition slot, CArtifactInstance * art)
  785. {
  786. setNewArtSlot(slot, art, false);
  787. if(art->artType->isCombined() && ArtifactUtils::isSlotEquipment(slot))
  788. {
  789. const CArtifactInstance * mainPart = nullptr;
  790. for(const auto & part : art->getPartsInfo())
  791. if(vstd::contains(part.art->artType->getPossibleSlots().at(bearerType()), slot)
  792. && (part.slot == ArtifactPosition::PRE_FIRST))
  793. {
  794. mainPart = part.art;
  795. break;
  796. }
  797. for(auto & part : art->getPartsInfo())
  798. {
  799. if(part.art != mainPart)
  800. {
  801. if(!part.art->artType->canBePutAt(this, part.slot))
  802. part.slot = ArtifactUtils::getArtAnyPosition(this, part.art->getTypeId());
  803. assert(ArtifactUtils::isSlotEquipment(part.slot));
  804. setNewArtSlot(part.slot, part.art, true);
  805. }
  806. }
  807. }
  808. }
  809. void CArtifactSet::removeArtifact(ArtifactPosition slot)
  810. {
  811. auto art = getArt(slot, false);
  812. if(art)
  813. {
  814. if(art->isCombined())
  815. {
  816. for(auto & part : art->getPartsInfo())
  817. {
  818. if(getArt(part.slot, false))
  819. eraseArtSlot(part.slot);
  820. }
  821. }
  822. eraseArtSlot(slot);
  823. }
  824. }
  825. std::pair<const CArtifactInstance *, const CArtifactInstance *> CArtifactSet::searchForConstituent(const ArtifactID & aid) const
  826. {
  827. for(const auto & slot : artifactsInBackpack)
  828. {
  829. auto art = slot.artifact;
  830. if(art->isCombined())
  831. {
  832. for(auto & ci : art->getPartsInfo())
  833. {
  834. if(ci.art->getTypeId() == aid)
  835. {
  836. return {art, ci.art};
  837. }
  838. }
  839. }
  840. }
  841. return {nullptr, nullptr};
  842. }
  843. const CArtifactInstance * CArtifactSet::getHiddenArt(const ArtifactID & aid) const
  844. {
  845. return searchForConstituent(aid).second;
  846. }
  847. const CArtifactInstance * CArtifactSet::getAssemblyByConstituent(const ArtifactID & aid) const
  848. {
  849. return searchForConstituent(aid).first;
  850. }
  851. const ArtSlotInfo * CArtifactSet::getSlot(const ArtifactPosition & pos) const
  852. {
  853. if(pos == ArtifactPosition::TRANSITION_POS)
  854. {
  855. // Always add to the end. Always take from the beginning.
  856. if(artifactsTransitionPos.empty())
  857. return nullptr;
  858. else
  859. return &(*artifactsTransitionPos.begin());
  860. }
  861. if(vstd::contains(artifactsWorn, pos))
  862. return &artifactsWorn.at(pos);
  863. if(pos >= ArtifactPosition::AFTER_LAST )
  864. {
  865. int backpackPos = (int)pos - GameConstants::BACKPACK_START;
  866. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  867. return nullptr;
  868. else
  869. return &artifactsInBackpack[backpackPos];
  870. }
  871. return nullptr;
  872. }
  873. bool CArtifactSet::isPositionFree(const ArtifactPosition & pos, bool onlyLockCheck) const
  874. {
  875. if(const ArtSlotInfo *s = getSlot(pos))
  876. return (onlyLockCheck || !s->artifact) && !s->locked;
  877. return true; //no slot means not used
  878. }
  879. void CArtifactSet::setNewArtSlot(const ArtifactPosition & slot, CArtifactInstance * art, bool locked)
  880. {
  881. assert(!vstd::contains(artifactsWorn, slot));
  882. ArtSlotInfo * slotInfo;
  883. if(slot == ArtifactPosition::TRANSITION_POS)
  884. {
  885. // Always add to the end. Always take from the beginning.
  886. artifactsTransitionPos.emplace_back();
  887. slotInfo = &artifactsTransitionPos.back();
  888. }
  889. else if(ArtifactUtils::isSlotEquipment(slot))
  890. {
  891. slotInfo = &artifactsWorn[slot];
  892. }
  893. else
  894. {
  895. auto position = artifactsInBackpack.begin() + slot - GameConstants::BACKPACK_START;
  896. slotInfo = &(*artifactsInBackpack.emplace(position, ArtSlotInfo()));
  897. }
  898. slotInfo->artifact = art;
  899. slotInfo->locked = locked;
  900. }
  901. void CArtifactSet::eraseArtSlot(const ArtifactPosition & slot)
  902. {
  903. if(slot == ArtifactPosition::TRANSITION_POS)
  904. {
  905. assert(!artifactsTransitionPos.empty());
  906. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  907. }
  908. else if(ArtifactUtils::isSlotBackpack(slot))
  909. {
  910. auto backpackSlot = ArtifactPosition(slot - GameConstants::BACKPACK_START);
  911. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  912. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  913. }
  914. else
  915. {
  916. artifactsWorn.erase(slot);
  917. }
  918. }
  919. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  920. {
  921. for(auto & elem : artifactsWorn)
  922. if(elem.second.artifact && !elem.second.locked)
  923. node->attachTo(*elem.second.artifact);
  924. }
  925. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  926. {
  927. //todo: creature and commander artifacts
  928. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  929. return;
  930. if(!handler.saving)
  931. {
  932. assert(map);
  933. artifactsInBackpack.clear();
  934. artifactsWorn.clear();
  935. }
  936. auto s = handler.enterStruct(fieldName);
  937. switch(bearerType())
  938. {
  939. case ArtBearer::HERO:
  940. serializeJsonHero(handler, map);
  941. break;
  942. case ArtBearer::CREATURE:
  943. serializeJsonCreature(handler, map);
  944. break;
  945. case ArtBearer::COMMANDER:
  946. serializeJsonCommander(handler, map);
  947. break;
  948. default:
  949. assert(false);
  950. break;
  951. }
  952. }
  953. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  954. {
  955. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  956. {
  957. serializeJsonSlot(handler, ap, map);
  958. }
  959. std::vector<ArtifactID> backpackTemp;
  960. if(handler.saving)
  961. {
  962. backpackTemp.reserve(artifactsInBackpack.size());
  963. for(const ArtSlotInfo & info : artifactsInBackpack)
  964. backpackTemp.push_back(info.artifact->getTypeId());
  965. }
  966. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  967. if(!handler.saving)
  968. {
  969. for(const ArtifactID & artifactID : backpackTemp)
  970. {
  971. auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
  972. auto slot = ArtifactPosition(GameConstants::BACKPACK_START + (si32)artifactsInBackpack.size());
  973. if(artifact->artType->canBePutAt(this, slot))
  974. putArtifact(slot, artifact);
  975. }
  976. }
  977. }
  978. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  979. {
  980. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  981. }
  982. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  983. {
  984. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  985. }
  986. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  987. {
  988. ArtifactID artifactID;
  989. if(handler.saving)
  990. {
  991. const ArtSlotInfo * info = getSlot(slot);
  992. if(info != nullptr && !info->locked)
  993. {
  994. artifactID = info->artifact->getTypeId();
  995. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  996. }
  997. }
  998. else
  999. {
  1000. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1001. if(artifactID != ArtifactID::NONE)
  1002. {
  1003. auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
  1004. if(artifact->artType->canBePutAt(this, slot))
  1005. {
  1006. putArtifact(slot, artifact);
  1007. }
  1008. else
  1009. {
  1010. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  1011. }
  1012. }
  1013. }
  1014. }
  1015. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer):
  1016. Bearer(Bearer)
  1017. {
  1018. }
  1019. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  1020. {
  1021. return this->Bearer;
  1022. }
  1023. VCMI_LIB_NAMESPACE_END