CHeroHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. /*
  2. * CHeroHandler.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 "CHeroHandler.h"
  12. #include "CGeneralTextHandler.h"
  13. #include "filesystem/Filesystem.h"
  14. #include "VCMI_Lib.h"
  15. #include "JsonNode.h"
  16. #include "constants/StringConstants.h"
  17. #include "battle/BattleHex.h"
  18. #include "CCreatureHandler.h"
  19. #include "GameSettings.h"
  20. #include "CTownHandler.h"
  21. #include "CSkillHandler.h"
  22. #include "BattleFieldHandler.h"
  23. #include "bonuses/Limiters.h"
  24. #include "bonuses/Updaters.h"
  25. #include "mapObjectConstructors/AObjectTypeHandler.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.h"
  27. #include "modding/IdentifierStorage.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. CHero::CHero() = default;
  30. CHero::~CHero() = default;
  31. int32_t CHero::getIndex() const
  32. {
  33. return ID.getNum();
  34. }
  35. int32_t CHero::getIconIndex() const
  36. {
  37. return imageIndex;
  38. }
  39. std::string CHero::getJsonKey() const
  40. {
  41. return modScope + ':' + identifier;;
  42. }
  43. HeroTypeID CHero::getId() const
  44. {
  45. return ID;
  46. }
  47. std::string CHero::getNameTranslated() const
  48. {
  49. return VLC->generaltexth->translate(getNameTextID());
  50. }
  51. std::string CHero::getBiographyTranslated() const
  52. {
  53. return VLC->generaltexth->translate(getBiographyTextID());
  54. }
  55. std::string CHero::getSpecialtyNameTranslated() const
  56. {
  57. return VLC->generaltexth->translate(getSpecialtyNameTextID());
  58. }
  59. std::string CHero::getSpecialtyDescriptionTranslated() const
  60. {
  61. return VLC->generaltexth->translate(getSpecialtyDescriptionTextID());
  62. }
  63. std::string CHero::getSpecialtyTooltipTranslated() const
  64. {
  65. return VLC->generaltexth->translate(getSpecialtyTooltipTextID());
  66. }
  67. std::string CHero::getNameTextID() const
  68. {
  69. return TextIdentifier("hero", modScope, identifier, "name").get();
  70. }
  71. std::string CHero::getBiographyTextID() const
  72. {
  73. return TextIdentifier("hero", modScope, identifier, "biography").get();
  74. }
  75. std::string CHero::getSpecialtyNameTextID() const
  76. {
  77. return TextIdentifier("hero", modScope, identifier, "specialty", "name").get();
  78. }
  79. std::string CHero::getSpecialtyDescriptionTextID() const
  80. {
  81. return TextIdentifier("hero", modScope, identifier, "specialty", "description").get();
  82. }
  83. std::string CHero::getSpecialtyTooltipTextID() const
  84. {
  85. return TextIdentifier("hero", modScope, identifier, "specialty", "tooltip").get();
  86. }
  87. void CHero::registerIcons(const IconRegistar & cb) const
  88. {
  89. cb(getIconIndex(), 0, "UN32", iconSpecSmall);
  90. cb(getIconIndex(), 0, "UN44", iconSpecLarge);
  91. cb(getIconIndex(), 0, "PORTRAITSLARGE", portraitLarge);
  92. cb(getIconIndex(), 0, "PORTRAITSSMALL", portraitSmall);
  93. }
  94. void CHero::updateFrom(const JsonNode & data)
  95. {
  96. //todo: CHero::updateFrom
  97. }
  98. void CHero::serializeJson(JsonSerializeFormat & handler)
  99. {
  100. }
  101. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  102. {
  103. int totalProb = 0;
  104. for(const auto & possible : possibles)
  105. {
  106. totalProb += secSkillProbability[possible];
  107. }
  108. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  109. {
  110. auto ran = rand.nextInt(totalProb - 1);
  111. for(const auto & possible : possibles)
  112. {
  113. ran -= secSkillProbability[possible];
  114. if(ran < 0)
  115. {
  116. return possible;
  117. }
  118. }
  119. }
  120. // FIXME: select randomly? How H3 handles such rare situation?
  121. return *possibles.begin();
  122. }
  123. bool CHeroClass::isMagicHero() const
  124. {
  125. return affinity == MAGIC;
  126. }
  127. EAlignment CHeroClass::getAlignment() const
  128. {
  129. return VLC->factions()->getByIndex(faction)->getAlignment();
  130. }
  131. int32_t CHeroClass::getIndex() const
  132. {
  133. return id.getNum();
  134. }
  135. int32_t CHeroClass::getIconIndex() const
  136. {
  137. return getIndex();
  138. }
  139. std::string CHeroClass::getJsonKey() const
  140. {
  141. return modScope + ':' + identifier;;
  142. }
  143. HeroClassID CHeroClass::getId() const
  144. {
  145. return id;
  146. }
  147. void CHeroClass::registerIcons(const IconRegistar & cb) const
  148. {
  149. }
  150. std::string CHeroClass::getNameTranslated() const
  151. {
  152. return VLC->generaltexth->translate(getNameTextID());
  153. }
  154. std::string CHeroClass::getNameTextID() const
  155. {
  156. return TextIdentifier("heroClass", modScope, identifier, "name").get();
  157. }
  158. void CHeroClass::updateFrom(const JsonNode & data)
  159. {
  160. //TODO: CHeroClass::updateFrom
  161. }
  162. void CHeroClass::serializeJson(JsonSerializeFormat & handler)
  163. {
  164. }
  165. CHeroClass::CHeroClass():
  166. faction(0),
  167. affinity(0),
  168. defaultTavernChance(0),
  169. commander(nullptr)
  170. {
  171. }
  172. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill pSkill) const
  173. {
  174. const auto & skillName = NPrimarySkill::names[static_cast<int>(pSkill)];
  175. auto currentPrimarySkillValue = static_cast<int>(node["primarySkills"][skillName].Integer());
  176. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  177. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  178. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  179. {
  180. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  181. heroClass->getNameTranslated(), currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  182. currentPrimarySkillValue = primarySkillLegalMinimum;
  183. }
  184. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  185. heroClass->primarySkillLowLevel.push_back(static_cast<int>(node["lowLevelChance"][skillName].Float()));
  186. heroClass->primarySkillHighLevel.push_back(static_cast<int>(node["highLevelChance"][skillName].Float()));
  187. }
  188. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  189. {
  190. static const std::vector<std::string> typeNames = { "heroClass" };
  191. return typeNames;
  192. }
  193. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  194. {
  195. assert(identifier.find(':') == std::string::npos);
  196. assert(!scope.empty());
  197. std::string affinityStr[2] = { "might", "magic" };
  198. auto * heroClass = new CHeroClass();
  199. heroClass->id = HeroClassID(index);
  200. heroClass->identifier = identifier;
  201. heroClass->modScope = scope;
  202. heroClass->imageBattleFemale = AnimationPath::fromJson(node["animation"]["battle"]["female"]);
  203. heroClass->imageBattleMale = AnimationPath::fromJson(node["animation"]["battle"]["male"]);
  204. //MODS COMPATIBILITY FOR 0.96
  205. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  206. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  207. VLC->generaltexth->registerString(scope, heroClass->getNameTextID(), node["name"].String());
  208. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  209. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  210. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  211. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  212. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  213. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  214. if(percentSumm != 100)
  215. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  216. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  217. if(percentSumm != 100)
  218. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  219. for(auto skillPair : node["secondarySkills"].Struct())
  220. {
  221. int probability = static_cast<int>(skillPair.second.Integer());
  222. VLC->identifiers()->requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  223. {
  224. if(heroClass->secSkillProbability.size() <= skillID)
  225. heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
  226. heroClass->secSkillProbability[skillID] = probability;
  227. });
  228. }
  229. VLC->identifiers()->requestIdentifier ("creature", node["commander"],
  230. [=](si32 commanderID)
  231. {
  232. heroClass->commander = VLC->creh->objects[commanderID];
  233. });
  234. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  235. for(const auto & tavern : node["tavern"].Struct())
  236. {
  237. int value = static_cast<int>(tavern.second.Float());
  238. VLC->identifiers()->requestIdentifier(tavern.second.meta, "faction", tavern.first,
  239. [=](si32 factionID)
  240. {
  241. heroClass->selectionProbability[FactionID(factionID)] = value;
  242. });
  243. }
  244. VLC->identifiers()->requestIdentifier("faction", node["faction"],
  245. [=](si32 factionID)
  246. {
  247. heroClass->faction = factionID;
  248. });
  249. VLC->identifiers()->requestIdentifier(scope, "object", "hero", [=](si32 index)
  250. {
  251. JsonNode classConf = node["mapObject"];
  252. classConf["heroClass"].String() = identifier;
  253. classConf.setMeta(scope);
  254. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  255. });
  256. return heroClass;
  257. }
  258. std::vector<JsonNode> CHeroClassHandler::loadLegacyData()
  259. {
  260. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO_CLASS);
  261. objects.resize(dataSize);
  262. std::vector<JsonNode> h3Data;
  263. h3Data.reserve(dataSize);
  264. CLegacyConfigParser parser(TextPath::builtin("DATA/HCTRAITS.TXT"));
  265. parser.endLine(); // header
  266. parser.endLine();
  267. for (size_t i=0; i<dataSize; i++)
  268. {
  269. JsonNode entry;
  270. entry["name"].String() = parser.readString();
  271. parser.readNumber(); // unused aggression
  272. for(const auto & name : NPrimarySkill::names)
  273. entry["primarySkills"][name].Float() = parser.readNumber();
  274. for(const auto & name : NPrimarySkill::names)
  275. entry["lowLevelChance"][name].Float() = parser.readNumber();
  276. for(const auto & name : NPrimarySkill::names)
  277. entry["highLevelChance"][name].Float() = parser.readNumber();
  278. for(const auto & name : NSecondarySkill::names)
  279. entry["secondarySkills"][name].Float() = parser.readNumber();
  280. for(const auto & name : NFaction::names)
  281. entry["tavern"][name].Float() = parser.readNumber();
  282. parser.endLine();
  283. h3Data.push_back(entry);
  284. }
  285. return h3Data;
  286. }
  287. void CHeroClassHandler::afterLoadFinalization()
  288. {
  289. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  290. for(CHeroClass * heroClass : objects)
  291. {
  292. for(CFaction * faction : VLC->townh->objects)
  293. {
  294. if (!faction->town)
  295. continue;
  296. if (heroClass->selectionProbability.count(faction->getId()))
  297. continue;
  298. auto chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  299. heroClass->selectionProbability[faction->getId()] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  300. }
  301. // set default probabilities for gaining secondary skills where not loaded previously
  302. heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
  303. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  304. {
  305. if(heroClass->secSkillProbability[skillID] < 0)
  306. {
  307. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  308. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->getJsonKey());
  309. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  310. }
  311. }
  312. }
  313. for(CHeroClass * hc : objects)
  314. {
  315. if (!hc->imageMapMale.empty())
  316. {
  317. JsonNode templ;
  318. templ["animation"].String() = hc->imageMapMale;
  319. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  320. }
  321. }
  322. }
  323. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  324. {
  325. return std::vector<bool>(size(), true);
  326. }
  327. CHeroClassHandler::~CHeroClassHandler() = default;
  328. CHeroHandler::~CHeroHandler() = default;
  329. CHeroHandler::CHeroHandler()
  330. {
  331. loadExperience();
  332. }
  333. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  334. {
  335. static const std::vector<std::string> typeNames = { "hero" };
  336. return typeNames;
  337. }
  338. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  339. {
  340. assert(identifier.find(':') == std::string::npos);
  341. assert(!scope.empty());
  342. auto * hero = new CHero();
  343. hero->ID = HeroTypeID(index);
  344. hero->identifier = identifier;
  345. hero->modScope = scope;
  346. hero->gender = node["female"].Bool() ? EHeroGender::FEMALE : EHeroGender::MALE;
  347. hero->special = node["special"].Bool();
  348. //Default - both false
  349. hero->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  350. hero->onlyOnMapWithoutWater = node["onlyOnMapWithoutWater"].Bool();
  351. VLC->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"].String());
  352. VLC->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"].String());
  353. VLC->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  354. VLC->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  355. VLC->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"].String());
  356. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  357. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  358. hero->portraitSmall = node["images"]["small"].String();
  359. hero->portraitLarge = node["images"]["large"].String();
  360. hero->battleImage = AnimationPath::fromJson(node["battleImage"]);
  361. loadHeroArmy(hero, node);
  362. loadHeroSkills(hero, node);
  363. loadHeroSpecialty(hero, node);
  364. VLC->identifiers()->requestIdentifier("heroClass", node["class"],
  365. [=](si32 classID)
  366. {
  367. hero->heroClass = classes[HeroClassID(classID)];
  368. });
  369. return hero;
  370. }
  371. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node) const
  372. {
  373. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  374. hero->initialArmy.resize(node["army"].Vector().size());
  375. for (size_t i=0; i< hero->initialArmy.size(); i++)
  376. {
  377. const JsonNode & source = node["army"].Vector()[i];
  378. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  379. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  380. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  381. VLC->identifiers()->requestIdentifier("creature", source["creature"], [=](si32 creature)
  382. {
  383. hero->initialArmy[i].creature = CreatureID(creature);
  384. });
  385. }
  386. }
  387. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node) const
  388. {
  389. for(const JsonNode &set : node["skills"].Vector())
  390. {
  391. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  392. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  393. {
  394. size_t currentIndex = hero->secSkillsInit.size();
  395. hero->secSkillsInit.emplace_back(SecondarySkill(-1), skillLevel);
  396. VLC->identifiers()->requestIdentifier("skill", set["skill"], [=](si32 id)
  397. {
  398. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  399. });
  400. }
  401. else
  402. {
  403. logMod->error("Unknown skill level: %s", set["level"].String());
  404. }
  405. }
  406. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  407. hero->haveSpellBook = !node["spellbook"].isNull();
  408. for(const JsonNode & spell : node["spellbook"].Vector())
  409. {
  410. VLC->identifiers()->requestIdentifier("spell", spell,
  411. [=](si32 spellID)
  412. {
  413. hero->spells.insert(SpellID(spellID));
  414. });
  415. }
  416. }
  417. /// creates standard H3 hero specialty for creatures
  418. static std::vector<std::shared_ptr<Bonus>> createCreatureSpecialty(CreatureID baseCreatureID)
  419. {
  420. std::vector<std::shared_ptr<Bonus>> result;
  421. std::set<CreatureID> targets;
  422. targets.insert(baseCreatureID);
  423. // go through entire upgrade chain and collect all creatures to which baseCreatureID can be upgraded
  424. for (;;)
  425. {
  426. std::set<CreatureID> oldTargets = targets;
  427. for (auto const & upgradeSourceID : oldTargets)
  428. {
  429. const CCreature * upgradeSource = VLC->creh->objects[upgradeSourceID];
  430. targets.insert(upgradeSource->upgrades.begin(), upgradeSource->upgrades.end());
  431. }
  432. if (oldTargets.size() == targets.size())
  433. break;
  434. }
  435. for(CreatureID cid : targets)
  436. {
  437. const CCreature &specCreature = *VLC->creh->objects[cid];
  438. int stepSize = specCreature.getLevel() ? specCreature.getLevel() : 5;
  439. {
  440. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  441. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  442. bonus->type = BonusType::STACKS_SPEED;
  443. bonus->val = 1;
  444. result.push_back(bonus);
  445. }
  446. {
  447. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  448. bonus->type = BonusType::PRIMARY_SKILL;
  449. bonus->subtype = static_cast<int>(PrimarySkill::ATTACK);
  450. bonus->val = 0;
  451. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  452. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  453. result.push_back(bonus);
  454. }
  455. {
  456. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  457. bonus->type = BonusType::PRIMARY_SKILL;
  458. bonus->subtype = static_cast<int>(PrimarySkill::DEFENSE);
  459. bonus->val = 0;
  460. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  461. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  462. result.push_back(bonus);
  463. }
  464. }
  465. return result;
  466. }
  467. void CHeroHandler::beforeValidate(JsonNode & object)
  468. {
  469. //handle "base" specialty info
  470. JsonNode & specialtyNode = object["specialty"];
  471. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  472. {
  473. const JsonNode & base = specialtyNode["base"];
  474. if(!base.isNull())
  475. {
  476. if(specialtyNode["bonuses"].isNull())
  477. {
  478. logMod->warn("specialty has base without bonuses");
  479. }
  480. else
  481. {
  482. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  483. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  484. JsonUtils::inherit(bonuses[keyValue.first], base);
  485. }
  486. }
  487. }
  488. }
  489. void CHeroHandler::afterLoadFinalization()
  490. {
  491. for (auto const & functor : callAfterLoadFinalization)
  492. functor();
  493. callAfterLoadFinalization.clear();
  494. }
  495. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  496. {
  497. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  498. {
  499. bonus->duration = BonusDuration::PERMANENT;
  500. bonus->source = BonusSource::HERO_SPECIAL;
  501. bonus->sid = hero->getIndex();
  502. return bonus;
  503. };
  504. //new format, using bonus system
  505. const JsonNode & specialtyNode = node["specialty"];
  506. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  507. {
  508. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  509. return;
  510. }
  511. //creature specialty - alias for simplicity
  512. if(!specialtyNode["creature"].isNull())
  513. {
  514. JsonNode creatureNode = specialtyNode["creature"];
  515. std::function<void()> specialtyLoader = [creatureNode, hero, prepSpec]
  516. {
  517. VLC->identifiers()->requestIdentifier("creature", creatureNode, [hero, prepSpec](si32 creature)
  518. {
  519. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature)))
  520. hero->specialty.push_back(prepSpec(bonus));
  521. });
  522. };
  523. callAfterLoadFinalization.push_back(specialtyLoader);
  524. }
  525. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  526. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  527. }
  528. void CHeroHandler::loadExperience()
  529. {
  530. expPerLevel.push_back(0);
  531. expPerLevel.push_back(1000);
  532. expPerLevel.push_back(2000);
  533. expPerLevel.push_back(3200);
  534. expPerLevel.push_back(4600);
  535. expPerLevel.push_back(6200);
  536. expPerLevel.push_back(8000);
  537. expPerLevel.push_back(10000);
  538. expPerLevel.push_back(12200);
  539. expPerLevel.push_back(14700);
  540. expPerLevel.push_back(17500);
  541. expPerLevel.push_back(20600);
  542. expPerLevel.push_back(24320);
  543. expPerLevel.push_back(28784);
  544. expPerLevel.push_back(34140);
  545. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  546. {
  547. auto i = expPerLevel.size() - 1;
  548. auto diff = expPerLevel[i] - expPerLevel[i-1];
  549. diff += diff / 5;
  550. expPerLevel.push_back (expPerLevel[i] + diff);
  551. }
  552. expPerLevel.pop_back();//last value is broken
  553. }
  554. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  555. static std::string genRefName(std::string input)
  556. {
  557. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  558. input[0] = std::tolower(input[0]); // to camelCase
  559. return input;
  560. }
  561. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  562. {
  563. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO);
  564. objects.resize(dataSize);
  565. std::vector<JsonNode> h3Data;
  566. h3Data.reserve(dataSize);
  567. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  568. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  569. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  570. parser.endLine(); //ignore header
  571. parser.endLine();
  572. specParser.endLine(); //ignore header
  573. specParser.endLine();
  574. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  575. {
  576. JsonNode heroData;
  577. heroData["texts"]["name"].String() = parser.readString();
  578. heroData["texts"]["biography"].String() = bioParser.readString();
  579. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  580. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  581. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  582. for(int x=0;x<3;x++)
  583. {
  584. JsonNode armySlot;
  585. armySlot["min"].Float() = parser.readNumber();
  586. armySlot["max"].Float() = parser.readNumber();
  587. armySlot["creature"].String() = genRefName(parser.readString());
  588. heroData["army"].Vector().push_back(armySlot);
  589. }
  590. parser.endLine();
  591. specParser.endLine();
  592. bioParser.endLine();
  593. h3Data.push_back(heroData);
  594. }
  595. return h3Data;
  596. }
  597. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  598. {
  599. size_t index = objects.size();
  600. auto * object = loadFromJson(scope, data, name, index);
  601. object->imageIndex = static_cast<si32>(index) + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  602. objects.emplace_back(object);
  603. registerObject(scope, "hero", name, object->getIndex());
  604. }
  605. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  606. {
  607. auto * object = loadFromJson(scope, data, name, index);
  608. object->imageIndex = static_cast<si32>(index);
  609. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  610. objects[index] = object;
  611. registerObject(scope, "hero", name, object->getIndex());
  612. }
  613. ui32 CHeroHandler::level (ui64 experience) const
  614. {
  615. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  616. }
  617. ui64 CHeroHandler::reqExp (ui32 level) const
  618. {
  619. if(!level)
  620. return 0;
  621. if (level <= expPerLevel.size())
  622. {
  623. return expPerLevel[level-1];
  624. }
  625. else
  626. {
  627. logGlobal->warn("A hero has reached unsupported amount of experience");
  628. return expPerLevel[expPerLevel.size()-1];
  629. }
  630. }
  631. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  632. {
  633. // Look Data/HOTRAITS.txt for reference
  634. std::vector<bool> allowedHeroes;
  635. allowedHeroes.reserve(size());
  636. for(const CHero * hero : objects)
  637. {
  638. allowedHeroes.push_back(hero && !hero->special);
  639. }
  640. return allowedHeroes;
  641. }
  642. VCMI_LIB_NAMESPACE_END