CHeroHandler.cpp 23 KB

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