CHeroHandler.cpp 24 KB

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