CArtHandler.cpp 32 KB

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