CHeroHandler.cpp 24 KB

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