CHeroHandler.cpp 24 KB

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