2
0

CHeroHandler.cpp 23 KB

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