CArtHandler.cpp 32 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 "CModHandler.h"
  15. #include "GameSettings.h"
  16. #include "mapObjects/MapObjects.h"
  17. #include "StringConstants.h"
  18. #include "mapObjectConstructors/AObjectTypeHandler.h"
  19. #include "mapObjectConstructors/CObjectClassesHandler.h"
  20. #include "serializer/JsonSerializeFormat.h"
  21. // Note: list must match entries in ArtTraits.txt
  22. #define ART_POS_LIST \
  23. ART_POS(SPELLBOOK) \
  24. ART_POS(MACH4) \
  25. ART_POS(MACH3) \
  26. ART_POS(MACH2) \
  27. ART_POS(MACH1) \
  28. ART_POS(MISC5) \
  29. ART_POS(MISC4) \
  30. ART_POS(MISC3) \
  31. ART_POS(MISC2) \
  32. ART_POS(MISC1) \
  33. ART_POS(FEET) \
  34. ART_POS(LEFT_RING) \
  35. ART_POS(RIGHT_RING) \
  36. ART_POS(TORSO) \
  37. ART_POS(LEFT_HAND) \
  38. ART_POS(RIGHT_HAND) \
  39. ART_POS(NECK) \
  40. ART_POS(SHOULDERS) \
  41. ART_POS(HEAD)
  42. VCMI_LIB_NAMESPACE_BEGIN
  43. bool CCombinedArtifact::isCombined() const
  44. {
  45. return !(constituents.empty());
  46. }
  47. const std::vector<CArtifact*> & CCombinedArtifact::getConstituents() const
  48. {
  49. return constituents;
  50. }
  51. const std::vector<CArtifact*> & CCombinedArtifact::getPartOf() const
  52. {
  53. return partOf;
  54. }
  55. bool CScrollArtifact::isScroll() const
  56. {
  57. return static_cast<const CArtifact*>(this)->getId() == ArtifactID::SPELL_SCROLL;
  58. }
  59. bool CGrowingArtifact::isGrowing() const
  60. {
  61. return !bonusesPerLevel.empty() || !thresholdBonuses.empty();
  62. }
  63. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel()
  64. {
  65. return bonusesPerLevel;
  66. }
  67. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel() const
  68. {
  69. return bonusesPerLevel;
  70. }
  71. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses()
  72. {
  73. return thresholdBonuses;
  74. }
  75. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses() const
  76. {
  77. return thresholdBonuses;
  78. }
  79. int32_t CArtifact::getIndex() const
  80. {
  81. return id.toEnum();
  82. }
  83. int32_t CArtifact::getIconIndex() const
  84. {
  85. return iconIndex;
  86. }
  87. std::string CArtifact::getJsonKey() const
  88. {
  89. return modScope + ':' + identifier;
  90. }
  91. void CArtifact::registerIcons(const IconRegistar & cb) const
  92. {
  93. cb(getIconIndex(), 0, "ARTIFACT", image);
  94. cb(getIconIndex(), 0, "ARTIFACTLARGE", large);
  95. }
  96. ArtifactID CArtifact::getId() const
  97. {
  98. return id;
  99. }
  100. const IBonusBearer * CArtifact::getBonusBearer() const
  101. {
  102. return this;
  103. }
  104. std::string CArtifact::getDescriptionTranslated() const
  105. {
  106. return VLC->generaltexth->translate(getDescriptionTextID());
  107. }
  108. std::string CArtifact::getEventTranslated() const
  109. {
  110. return VLC->generaltexth->translate(getEventTextID());
  111. }
  112. std::string CArtifact::getNameTranslated() const
  113. {
  114. return VLC->generaltexth->translate(getNameTextID());
  115. }
  116. std::string CArtifact::getDescriptionTextID() const
  117. {
  118. return TextIdentifier("artifact", modScope, identifier, "description").get();
  119. }
  120. std::string CArtifact::getEventTextID() const
  121. {
  122. return TextIdentifier("artifact", modScope, identifier, "event").get();
  123. }
  124. std::string CArtifact::getNameTextID() const
  125. {
  126. return TextIdentifier("artifact", modScope, identifier, "name").get();
  127. }
  128. uint32_t CArtifact::getPrice() const
  129. {
  130. return price;
  131. }
  132. CreatureID CArtifact::getWarMachine() const
  133. {
  134. return warMachine;
  135. }
  136. bool CArtifact::isBig() const
  137. {
  138. return warMachine != CreatureID::NONE;
  139. }
  140. bool CArtifact::isTradable() const
  141. {
  142. switch(id)
  143. {
  144. case ArtifactID::SPELLBOOK:
  145. case ArtifactID::GRAIL:
  146. return false;
  147. default:
  148. return !isBig();
  149. }
  150. }
  151. bool CArtifact::canBePutAt(const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  152. {
  153. auto simpleArtCanBePutAt = [this](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  154. {
  155. if(ArtifactUtils::isSlotBackpack(slot))
  156. {
  157. if(isBig() || !ArtifactUtils::isBackpackFreeSlots(artSet))
  158. return false;
  159. return true;
  160. }
  161. if(!vstd::contains(possibleSlots.at(artSet->bearerType()), slot))
  162. return false;
  163. return artSet->isPositionFree(slot, assumeDestRemoved);
  164. };
  165. auto artCanBePutAt = [this, simpleArtCanBePutAt](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  166. {
  167. if(isCombined())
  168. {
  169. if(!simpleArtCanBePutAt(artSet, slot, assumeDestRemoved))
  170. return false;
  171. if(ArtifactUtils::isSlotBackpack(slot))
  172. return true;
  173. CArtifactFittingSet fittingSet(artSet->bearerType());
  174. fittingSet.artifactsWorn = artSet->artifactsWorn;
  175. if(assumeDestRemoved)
  176. fittingSet.removeArtifact(slot);
  177. for(const auto art : constituents)
  178. {
  179. auto possibleSlot = ArtifactUtils::getArtAnyPosition(&fittingSet, art->getId());
  180. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  181. {
  182. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  183. }
  184. else
  185. {
  186. return false;
  187. }
  188. }
  189. return true;
  190. }
  191. else
  192. {
  193. return simpleArtCanBePutAt(artSet, slot, assumeDestRemoved);
  194. }
  195. };
  196. if(slot == ArtifactPosition::TRANSITION_POS)
  197. return true;
  198. if(slot == ArtifactPosition::FIRST_AVAILABLE)
  199. {
  200. for(const auto & slot : possibleSlots.at(artSet->bearerType()))
  201. {
  202. if(artCanBePutAt(artSet, slot, assumeDestRemoved))
  203. return true;
  204. }
  205. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  206. }
  207. else if(ArtifactUtils::isSlotBackpack(slot))
  208. {
  209. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  210. }
  211. else
  212. {
  213. return artCanBePutAt(artSet, slot, assumeDestRemoved);
  214. }
  215. }
  216. CArtifact::CArtifact()
  217. : iconIndex(ArtifactID::NONE),
  218. price(0)
  219. {
  220. setNodeType(ARTIFACT);
  221. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  222. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  223. possibleSlots[ArtBearer::COMMANDER];
  224. }
  225. //This destructor should be placed here to avoid side effects
  226. CArtifact::~CArtifact() = default;
  227. int CArtifact::getArtClassSerial() const
  228. {
  229. if(id == ArtifactID::SPELL_SCROLL)
  230. return 4;
  231. switch(aClass)
  232. {
  233. case ART_TREASURE:
  234. return 0;
  235. case ART_MINOR:
  236. return 1;
  237. case ART_MAJOR:
  238. return 2;
  239. case ART_RELIC:
  240. return 3;
  241. case ART_SPECIAL:
  242. return 5;
  243. }
  244. return -1;
  245. }
  246. std::string CArtifact::nodeName() const
  247. {
  248. return "Artifact: " + getNameTranslated();
  249. }
  250. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  251. {
  252. b->source = BonusSource::ARTIFACT;
  253. b->duration = BonusDuration::PERMANENT;
  254. b->description = getNameTranslated();
  255. CBonusSystemNode::addNewBonus(b);
  256. }
  257. const std::map<ArtBearer::ArtBearer, std::vector<ArtifactPosition>> & CArtifact::getPossibleSlots() const
  258. {
  259. return possibleSlots;
  260. }
  261. void CArtifact::updateFrom(const JsonNode& data)
  262. {
  263. //TODO:CArtifact::updateFrom
  264. }
  265. void CArtifact::setImage(int32_t iconIndex, std::string image, std::string large)
  266. {
  267. this->iconIndex = iconIndex;
  268. this->image = image;
  269. this->large = large;
  270. }
  271. CArtHandler::~CArtHandler() = default;
  272. std::vector<JsonNode> CArtHandler::loadLegacyData()
  273. {
  274. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_ARTIFACT);
  275. objects.resize(dataSize);
  276. std::vector<JsonNode> h3Data;
  277. h3Data.reserve(dataSize);
  278. #define ART_POS(x) #x ,
  279. const std::vector<std::string> artSlots = { ART_POS_LIST };
  280. #undef ART_POS
  281. static std::map<char, std::string> classes =
  282. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  283. CLegacyConfigParser parser("DATA/ARTRAITS.TXT");
  284. CLegacyConfigParser events("DATA/ARTEVENT.TXT");
  285. parser.endLine(); // header
  286. parser.endLine();
  287. for (size_t i = 0; i < dataSize; i++)
  288. {
  289. JsonNode artData;
  290. artData["text"]["name"].String() = parser.readString();
  291. artData["text"]["event"].String() = events.readString();
  292. artData["value"].Float() = parser.readNumber();
  293. for(const auto & artSlot : artSlots)
  294. {
  295. if(parser.readString() == "x")
  296. {
  297. artData["slot"].Vector().push_back(JsonNode());
  298. artData["slot"].Vector().back().String() = artSlot;
  299. }
  300. }
  301. artData["class"].String() = classes[parser.readString()[0]];
  302. artData["text"]["description"].String() = parser.readString();
  303. parser.endLine();
  304. events.endLine();
  305. h3Data.push_back(artData);
  306. }
  307. return h3Data;
  308. }
  309. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  310. {
  311. auto * object = loadFromJson(scope, data, name, objects.size());
  312. object->iconIndex = object->getIndex() + 5;
  313. objects.emplace_back(object);
  314. registerObject(scope, "artifact", name, object->id);
  315. }
  316. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  317. {
  318. auto * object = loadFromJson(scope, data, name, index);
  319. object->iconIndex = object->getIndex();
  320. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  321. objects[index] = object;
  322. registerObject(scope, "artifact", name, object->id);
  323. }
  324. const std::vector<std::string> & CArtHandler::getTypeNames() const
  325. {
  326. static const std::vector<std::string> typeNames = { "artifact" };
  327. return typeNames;
  328. }
  329. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  330. {
  331. assert(identifier.find(':') == std::string::npos);
  332. assert(!scope.empty());
  333. CArtifact * art = new CArtifact();
  334. if(!node["growing"].isNull())
  335. {
  336. for(auto bonus : node["growing"]["bonusesPerLevel"].Vector())
  337. {
  338. art->bonusesPerLevel.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  339. JsonUtils::parseBonus(bonus["bonus"], &art->bonusesPerLevel.back().second);
  340. }
  341. for(auto bonus : node["growing"]["thresholdBonuses"].Vector())
  342. {
  343. art->thresholdBonuses.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  344. JsonUtils::parseBonus(bonus["bonus"], &art->thresholdBonuses.back().second);
  345. }
  346. }
  347. art->id = ArtifactID(index);
  348. art->identifier = identifier;
  349. art->modScope = scope;
  350. const JsonNode & text = node["text"];
  351. VLC->generaltexth->registerString(scope, art->getNameTextID(), text["name"].String());
  352. VLC->generaltexth->registerString(scope, art->getDescriptionTextID(), text["description"].String());
  353. VLC->generaltexth->registerString(scope, art->getEventTextID(), text["event"].String());
  354. const JsonNode & graphics = node["graphics"];
  355. art->image = graphics["image"].String();
  356. if(!graphics["large"].isNull())
  357. art->large = graphics["large"].String();
  358. else
  359. art->large = art->image;
  360. art->advMapDef = graphics["map"].String();
  361. art->price = static_cast<ui32>(node["value"].Float());
  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->modh->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->modh->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->modh->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