CHeroHandler.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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::EAlignment CHeroClass::getAlignment() const
  126. {
  127. return ((*VLC->townh)[faction]->alignment);
  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] = 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->getIndex()))
  295. continue;
  296. auto chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  297. heroClass->selectionProbability[faction->getIndex()] = 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. // add standard creature specialty to result
  413. void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
  414. {
  415. const CCreature &specBaseCreature = *VLC->creh->objects[creatureID]; //base creature in which we have specialty
  416. bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
  417. bonus->type = Bonus::STACKS_SPEED;
  418. bonus->valType = Bonus::ADDITIVE_VALUE;
  419. bonus->val = 1;
  420. result.push_back(bonus);
  421. // attack and defense may differ for upgraded creatures => separate bonuses
  422. std::vector<int> specTargets;
  423. specTargets.push_back(creatureID);
  424. specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());
  425. for(int cid : specTargets)
  426. {
  427. const CCreature &specCreature = *VLC->creh->objects[cid];
  428. bonus = std::make_shared<Bonus>(*bonus);
  429. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  430. bonus->type = Bonus::PRIMARY_SKILL;
  431. bonus->val = 0;
  432. int stepSize = specCreature.level ? specCreature.level : 5;
  433. bonus->subtype = PrimarySkill::ATTACK;
  434. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  435. result.push_back(bonus);
  436. bonus = std::make_shared<Bonus>(*bonus);
  437. bonus->subtype = PrimarySkill::DEFENSE;
  438. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  439. result.push_back(bonus);
  440. }
  441. }
  442. // convert deprecated format
  443. std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
  444. {
  445. std::vector<std::shared_ptr<Bonus>> result;
  446. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  447. bonus->duration = Bonus::PERMANENT;
  448. bonus->source = Bonus::HERO_SPECIAL;
  449. bonus->sid = sid;
  450. bonus->val = spec.val;
  451. switch (spec.type)
  452. {
  453. case 1: //creature specialty
  454. AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
  455. break;
  456. case 2: //secondary skill
  457. {
  458. auto params = BonusParams("SECONDARY_SKILL_PREMY", "", spec.subtype);
  459. bonus->type = params.type;
  460. if(params.subtypeRelevant)
  461. bonus->subtype = params.subtype;
  462. bonus->valType = Bonus::PERCENT_TO_TARGET_TYPE;
  463. bonus->targetSourceType = Bonus::SECONDARY_SKILL;
  464. bonus->updater.reset(new TimesHeroLevelUpdater());
  465. result.push_back(bonus);
  466. break;
  467. }
  468. case 3: //spell damage bonus, level dependent but calculated elsewhere
  469. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  470. bonus->subtype = spec.subtype;
  471. bonus->updater.reset(new TimesHeroLevelUpdater());
  472. result.push_back(bonus);
  473. break;
  474. case 4: //creature stat boost
  475. switch (spec.subtype)
  476. {
  477. case 1:
  478. bonus->type = Bonus::PRIMARY_SKILL;
  479. bonus->subtype = PrimarySkill::ATTACK;
  480. break;
  481. case 2:
  482. bonus->type = Bonus::PRIMARY_SKILL;
  483. bonus->subtype = PrimarySkill::DEFENSE;
  484. break;
  485. case 3:
  486. bonus->type = Bonus::CREATURE_DAMAGE;
  487. bonus->subtype = 0; //both min and max
  488. break;
  489. case 4:
  490. bonus->type = Bonus::STACK_HEALTH;
  491. break;
  492. case 5:
  493. bonus->type = Bonus::STACKS_SPEED;
  494. break;
  495. default:
  496. logMod->warn("Unknown subtype for specialty 4");
  497. return result;
  498. }
  499. bonus->valType = Bonus::ADDITIVE_VALUE;
  500. bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->objects[spec.additionalinfo], true));
  501. result.push_back(bonus);
  502. break;
  503. case 5: //spell damage bonus in percent
  504. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  505. bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
  506. bonus->subtype = spec.subtype; //spell id
  507. result.push_back(bonus);
  508. break;
  509. case 6: //damage bonus for bless (Adela)
  510. {
  511. auto limiter = std::make_shared<HasAnotherBonusLimiter>(Bonus::GENERAL_DAMAGE_PREMY,Bonus::SPELL_EFFECT);
  512. limiter->sid = spec.subtype; //spell id if you ever wanted to use it otherwise
  513. limiter->isSourceIDRelevant = true;
  514. bonus->type = Bonus::GENERAL_DAMAGE_PREMY;
  515. bonus->updater.reset(new TimesHeroLevelUpdater());
  516. bonus->addLimiter(limiter);
  517. result.push_back(bonus);
  518. break;
  519. }
  520. case 7: //maxed mastery for spell
  521. bonus->type = Bonus::SPELL;
  522. bonus->subtype = spec.subtype; //spell id
  523. bonus->val = 3; //to match MAXED_SPELL
  524. bonus->valType = Bonus::INDEPENDENT_MAX;
  525. result.push_back(bonus);
  526. break;
  527. case 8: //peculiar spells - enchantments
  528. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  529. bonus->subtype = spec.subtype; //spell id
  530. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  531. result.push_back(bonus);
  532. break;
  533. case 9: //upgrade creatures
  534. {
  535. const auto &creatures = VLC->creh->objects;
  536. bonus->type = Bonus::SPECIAL_UPGRADE;
  537. bonus->subtype = spec.subtype; //base id
  538. bonus->additionalInfo = spec.additionalinfo; //target id
  539. result.push_back(bonus);
  540. //propagate for regular upgrades of base creature
  541. for(const auto & cre_id : creatures[spec.subtype]->upgrades)
  542. {
  543. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  544. upgradeUpgradedVersion->subtype = cre_id;
  545. result.push_back(upgradeUpgradedVersion);
  546. }
  547. }
  548. break;
  549. case 10: //resource generation
  550. bonus->type = Bonus::GENERATE_RESOURCE;
  551. bonus->subtype = spec.subtype;
  552. result.push_back(bonus);
  553. break;
  554. case 11: //starting skill with mastery (Adrienne)
  555. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  556. break;
  557. case 12: //army speed
  558. bonus->type = Bonus::STACKS_SPEED;
  559. result.push_back(bonus);
  560. break;
  561. case 13: //Dragon bonuses (Mutare)
  562. bonus->type = Bonus::PRIMARY_SKILL;
  563. bonus->valType = Bonus::ADDITIVE_VALUE;
  564. switch(spec.subtype)
  565. {
  566. case 1:
  567. bonus->subtype = PrimarySkill::ATTACK;
  568. break;
  569. case 2:
  570. bonus->subtype = PrimarySkill::DEFENSE;
  571. break;
  572. }
  573. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  574. result.push_back(bonus);
  575. break;
  576. default:
  577. logMod->warn("Unknown hero specialty %d", spec.type);
  578. break;
  579. }
  580. return result;
  581. }
  582. void CHeroHandler::beforeValidate(JsonNode & object)
  583. {
  584. //handle "base" specialty info
  585. JsonNode & specialtyNode = object["specialty"];
  586. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  587. {
  588. const JsonNode & base = specialtyNode["base"];
  589. if(!base.isNull())
  590. {
  591. if(specialtyNode["bonuses"].isNull())
  592. {
  593. logMod->warn("specialty has base without bonuses");
  594. }
  595. else
  596. {
  597. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  598. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  599. JsonUtils::inherit(bonuses[keyValue.first], base);
  600. }
  601. }
  602. }
  603. }
  604. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node) const
  605. {
  606. int sid = hero->ID.getNum();
  607. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  608. {
  609. bonus->duration = Bonus::PERMANENT;
  610. bonus->source = Bonus::HERO_SPECIAL;
  611. bonus->sid = sid;
  612. return bonus;
  613. };
  614. //new format, using bonus system
  615. const JsonNode & specialtyNode = node["specialty"];
  616. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  617. {
  618. //creature specialty - alias for simplicity
  619. if(!specialtyNode["creature"].isNull())
  620. {
  621. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  622. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  623. SSpecialtyInfo spec{};
  624. spec.type = 1;
  625. spec.additionalinfo = creature;
  626. hero->specDeprecated.push_back(spec);
  627. });
  628. }
  629. if(!specialtyNode["bonuses"].isNull())
  630. {
  631. //proper new format
  632. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  633. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  634. }
  635. }
  636. else
  637. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  638. }
  639. void CHeroHandler::loadExperience()
  640. {
  641. expPerLevel.push_back(0);
  642. expPerLevel.push_back(1000);
  643. expPerLevel.push_back(2000);
  644. expPerLevel.push_back(3200);
  645. expPerLevel.push_back(4600);
  646. expPerLevel.push_back(6200);
  647. expPerLevel.push_back(8000);
  648. expPerLevel.push_back(10000);
  649. expPerLevel.push_back(12200);
  650. expPerLevel.push_back(14700);
  651. expPerLevel.push_back(17500);
  652. expPerLevel.push_back(20600);
  653. expPerLevel.push_back(24320);
  654. expPerLevel.push_back(28784);
  655. expPerLevel.push_back(34140);
  656. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  657. {
  658. auto i = expPerLevel.size() - 1;
  659. auto diff = expPerLevel[i] - expPerLevel[i-1];
  660. diff += diff / 5;
  661. expPerLevel.push_back (expPerLevel[i] + diff);
  662. }
  663. expPerLevel.pop_back();//last value is broken
  664. }
  665. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  666. static std::string genRefName(std::string input)
  667. {
  668. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  669. input[0] = std::tolower(input[0]); // to camelCase
  670. return input;
  671. }
  672. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  673. {
  674. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO);
  675. objects.resize(dataSize);
  676. std::vector<JsonNode> h3Data;
  677. h3Data.reserve(dataSize);
  678. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  679. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  680. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  681. parser.endLine(); //ignore header
  682. parser.endLine();
  683. specParser.endLine(); //ignore header
  684. specParser.endLine();
  685. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  686. {
  687. JsonNode heroData;
  688. heroData["texts"]["name"].String() = parser.readString();
  689. heroData["texts"]["biography"].String() = bioParser.readString();
  690. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  691. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  692. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  693. for(int x=0;x<3;x++)
  694. {
  695. JsonNode armySlot;
  696. armySlot["min"].Float() = parser.readNumber();
  697. armySlot["max"].Float() = parser.readNumber();
  698. armySlot["creature"].String() = genRefName(parser.readString());
  699. heroData["army"].Vector().push_back(armySlot);
  700. }
  701. parser.endLine();
  702. specParser.endLine();
  703. bioParser.endLine();
  704. h3Data.push_back(heroData);
  705. }
  706. return h3Data;
  707. }
  708. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  709. {
  710. size_t index = objects.size();
  711. auto * object = loadFromJson(scope, data, name, index);
  712. object->imageIndex = static_cast<si32>(index) + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  713. objects.emplace_back(object);
  714. registerObject(scope, "hero", name, object->getIndex());
  715. }
  716. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  717. {
  718. auto * object = loadFromJson(scope, data, name, index);
  719. object->imageIndex = static_cast<si32>(index);
  720. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  721. objects[index] = object;
  722. registerObject(scope, "hero", name, object->getIndex());
  723. }
  724. void CHeroHandler::afterLoadFinalization()
  725. {
  726. for(auto & hero : objects)
  727. {
  728. for(const auto & bonus : hero->specialty)
  729. {
  730. bonus->sid = hero->getIndex();
  731. }
  732. if(!hero->specDeprecated.empty())
  733. {
  734. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  735. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  736. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  737. {
  738. for(const std::shared_ptr<Bonus> & b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  739. convertedBonuses.push_back(b);
  740. }
  741. hero->specDeprecated.clear();
  742. // store and create json for logging
  743. std::vector<JsonNode> specVec;
  744. std::vector<std::string> specNames;
  745. for(const std::shared_ptr<Bonus> & bonus : convertedBonuses)
  746. {
  747. hero->specialty.push_back(bonus);
  748. specVec.push_back(bonus->toJsonNode());
  749. // find fitting & unique bonus name
  750. std::string bonusName = bonus->nameForBonus();
  751. if(vstd::contains(specNames, bonusName))
  752. {
  753. int suffix = 2;
  754. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  755. suffix++;
  756. bonusName += std::to_string(suffix);
  757. }
  758. specNames.push_back(bonusName);
  759. }
  760. // log new format for easy copy-and-paste
  761. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  762. if(specVec.size() > 1)
  763. {
  764. JsonNode base = JsonUtils::intersect(specVec);
  765. if(base.containsBaseData())
  766. {
  767. specNode["base"] = base;
  768. for(JsonNode & node : specVec)
  769. node = JsonUtils::difference(node, base);
  770. }
  771. }
  772. // add json for bonuses
  773. specNode["bonuses"].Struct();
  774. for(int i = 0; i < specVec.size(); i++)
  775. specNode["bonuses"][specNames[i]] = specVec[i];
  776. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  777. }
  778. }
  779. }
  780. ui32 CHeroHandler::level (ui64 experience) const
  781. {
  782. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  783. }
  784. ui64 CHeroHandler::reqExp (ui32 level) const
  785. {
  786. if(!level)
  787. return 0;
  788. if (level <= expPerLevel.size())
  789. {
  790. return expPerLevel[level-1];
  791. }
  792. else
  793. {
  794. logGlobal->warn("A hero has reached unsupported amount of experience");
  795. return expPerLevel[expPerLevel.size()-1];
  796. }
  797. }
  798. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  799. {
  800. // Look Data/HOTRAITS.txt for reference
  801. std::vector<bool> allowedHeroes;
  802. allowedHeroes.reserve(size());
  803. for(const CHero * hero : objects)
  804. {
  805. allowedHeroes.push_back(!hero->special);
  806. }
  807. return allowedHeroes;
  808. }
  809. VCMI_LIB_NAMESPACE_END