CHeroHandler.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 "CModHandler.h"
  20. #include "CTownHandler.h"
  21. #include "mapObjects/CObjectHandler.h" //for hero specialty
  22. #include "CSkillHandler.h"
  23. #include <math.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(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(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 EAlignment::EAlignment((*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), id(), affinity(0), defaultTavernChance(0), commander(nullptr)
  165. {
  166. }
  167. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill::PrimarySkill pSkill)
  168. {
  169. const auto & skillName = PrimarySkill::names[pSkill];
  170. auto currentPrimarySkillValue = (int)node["primarySkills"][skillName].Integer();
  171. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  172. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  173. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  174. {
  175. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  176. heroClass->getNameTranslated(), currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  177. currentPrimarySkillValue = primarySkillLegalMinimum;
  178. }
  179. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  180. heroClass->primarySkillLowLevel.push_back((int)node["lowLevelChance"][skillName].Float());
  181. heroClass->primarySkillHighLevel.push_back((int)node["highLevelChance"][skillName].Float());
  182. }
  183. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  184. {
  185. static const std::vector<std::string> typeNames = { "heroClass" };
  186. return typeNames;
  187. }
  188. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  189. {
  190. assert(identifier.find(':') == std::string::npos);
  191. assert(!scope.empty());
  192. std::string affinityStr[2] = { "might", "magic" };
  193. auto heroClass = new CHeroClass();
  194. heroClass->id = HeroClassID(index);
  195. heroClass->identifier = identifier;
  196. heroClass->modScope = scope;
  197. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  198. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  199. //MODS COMPATIBILITY FOR 0.96
  200. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  201. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  202. VLC->generaltexth->registerString(scope, heroClass->getNameTextID(), node["name"].String());
  203. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  204. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  205. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  206. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  207. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  208. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  209. if(percentSumm != 100)
  210. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  211. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  212. if(percentSumm != 100)
  213. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  214. for(auto skillPair : node["secondarySkills"].Struct())
  215. {
  216. int probability = static_cast<int>(skillPair.second.Integer());
  217. VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  218. {
  219. if(heroClass->secSkillProbability.size() <= skillID)
  220. heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
  221. heroClass->secSkillProbability[skillID] = probability;
  222. });
  223. }
  224. VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
  225. [=](si32 commanderID)
  226. {
  227. heroClass->commander = VLC->creh->objects[commanderID];
  228. });
  229. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  230. for(auto & tavern : node["tavern"].Struct())
  231. {
  232. int value = static_cast<int>(tavern.second.Float());
  233. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  234. [=](si32 factionID)
  235. {
  236. heroClass->selectionProbability[factionID] = value;
  237. });
  238. }
  239. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  240. [=](si32 factionID)
  241. {
  242. heroClass->faction = factionID;
  243. });
  244. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  245. {
  246. JsonNode classConf = node["mapObject"];
  247. classConf["heroClass"].String() = identifier;
  248. classConf.setMeta(scope);
  249. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  250. });
  251. return heroClass;
  252. }
  253. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  254. {
  255. objects.resize(dataSize);
  256. std::vector<JsonNode> h3Data;
  257. h3Data.reserve(dataSize);
  258. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  259. parser.endLine(); // header
  260. parser.endLine();
  261. for (size_t i=0; i<dataSize; i++)
  262. {
  263. JsonNode entry;
  264. entry["name"].String() = parser.readString();
  265. parser.readNumber(); // unused aggression
  266. for (auto & name : PrimarySkill::names)
  267. entry["primarySkills"][name].Float() = parser.readNumber();
  268. for (auto & name : PrimarySkill::names)
  269. entry["lowLevelChance"][name].Float() = parser.readNumber();
  270. for (auto & name : PrimarySkill::names)
  271. entry["highLevelChance"][name].Float() = parser.readNumber();
  272. for (auto & name : NSecondarySkill::names)
  273. entry["secondarySkills"][name].Float() = parser.readNumber();
  274. for(auto & name : ETownType::names)
  275. entry["tavern"][name].Float() = parser.readNumber();
  276. parser.endLine();
  277. h3Data.push_back(entry);
  278. }
  279. return h3Data;
  280. }
  281. void CHeroClassHandler::afterLoadFinalization()
  282. {
  283. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  284. for(CHeroClass * heroClass : objects)
  285. {
  286. for(CFaction * faction : VLC->townh->objects)
  287. {
  288. if (!faction->town)
  289. continue;
  290. if (heroClass->selectionProbability.count(faction->getIndex()))
  291. continue;
  292. float chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  293. heroClass->selectionProbability[faction->getIndex()] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  294. }
  295. // set default probabilities for gaining secondary skills where not loaded previously
  296. heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
  297. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  298. {
  299. if(heroClass->secSkillProbability[skillID] < 0)
  300. {
  301. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  302. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->getJsonKey());
  303. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  304. }
  305. }
  306. }
  307. for(CHeroClass * hc : objects)
  308. {
  309. if (!hc->imageMapMale.empty())
  310. {
  311. JsonNode templ;
  312. templ["animation"].String() = hc->imageMapMale;
  313. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  314. }
  315. }
  316. }
  317. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  318. {
  319. return std::vector<bool>(size(), true);
  320. }
  321. CHeroClassHandler::~CHeroClassHandler() = default;
  322. CHeroHandler::~CHeroHandler() = default;
  323. CHeroHandler::CHeroHandler()
  324. {
  325. loadExperience();
  326. }
  327. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  328. {
  329. static const std::vector<std::string> typeNames = { "hero" };
  330. return typeNames;
  331. }
  332. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  333. {
  334. assert(identifier.find(':') == std::string::npos);
  335. assert(!scope.empty());
  336. auto hero = new CHero();
  337. hero->ID = HeroTypeID(index);
  338. hero->identifier = identifier;
  339. hero->modScope = scope;
  340. hero->sex = node["female"].Bool();
  341. hero->special = node["special"].Bool();
  342. VLC->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"].String());
  343. VLC->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"].String());
  344. VLC->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  345. VLC->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  346. VLC->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"].String());
  347. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  348. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  349. hero->portraitSmall = node["images"]["small"].String();
  350. hero->portraitLarge = node["images"]["large"].String();
  351. hero->battleImage = node["battleImage"].String();
  352. loadHeroArmy(hero, node);
  353. loadHeroSkills(hero, node);
  354. loadHeroSpecialty(hero, node);
  355. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  356. [=](si32 classID)
  357. {
  358. hero->heroClass = classes[HeroClassID(classID)];
  359. });
  360. return hero;
  361. }
  362. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  363. {
  364. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  365. hero->initialArmy.resize(node["army"].Vector().size());
  366. for (size_t i=0; i< hero->initialArmy.size(); i++)
  367. {
  368. const JsonNode & source = node["army"].Vector()[i];
  369. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  370. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  371. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  372. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  373. {
  374. hero->initialArmy[i].creature = CreatureID(creature);
  375. });
  376. }
  377. }
  378. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  379. {
  380. for(const JsonNode &set : node["skills"].Vector())
  381. {
  382. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  383. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  384. {
  385. size_t currentIndex = hero->secSkillsInit.size();
  386. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  387. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  388. {
  389. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  390. });
  391. }
  392. else
  393. {
  394. logMod->error("Unknown skill level: %s", set["level"].String());
  395. }
  396. }
  397. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  398. hero->haveSpellBook = !node["spellbook"].isNull();
  399. for(const JsonNode & spell : node["spellbook"].Vector())
  400. {
  401. VLC->modh->identifiers.requestIdentifier("spell", spell,
  402. [=](si32 spellID)
  403. {
  404. hero->spells.insert(SpellID(spellID));
  405. });
  406. }
  407. }
  408. // add standard creature specialty to result
  409. void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
  410. {
  411. const CCreature &specBaseCreature = *VLC->creh->objects[creatureID]; //base creature in which we have specialty
  412. bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
  413. bonus->type = Bonus::STACKS_SPEED;
  414. bonus->valType = Bonus::ADDITIVE_VALUE;
  415. bonus->val = 1;
  416. result.push_back(bonus);
  417. // attack and defense may differ for upgraded creatures => separate bonuses
  418. std::vector<int> specTargets;
  419. specTargets.push_back(creatureID);
  420. specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());
  421. for(int cid : specTargets)
  422. {
  423. const CCreature &specCreature = *VLC->creh->objects[cid];
  424. bonus = std::make_shared<Bonus>(*bonus);
  425. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  426. bonus->type = Bonus::PRIMARY_SKILL;
  427. bonus->val = 0;
  428. int stepSize = specCreature.level ? specCreature.level : 5;
  429. bonus->subtype = PrimarySkill::ATTACK;
  430. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  431. result.push_back(bonus);
  432. bonus = std::make_shared<Bonus>(*bonus);
  433. bonus->subtype = PrimarySkill::DEFENSE;
  434. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  435. result.push_back(bonus);
  436. }
  437. }
  438. // convert deprecated format
  439. std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
  440. {
  441. std::vector<std::shared_ptr<Bonus>> result;
  442. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  443. bonus->duration = Bonus::PERMANENT;
  444. bonus->source = Bonus::HERO_SPECIAL;
  445. bonus->sid = sid;
  446. bonus->val = spec.val;
  447. switch (spec.type)
  448. {
  449. case 1: //creature specialty
  450. AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
  451. break;
  452. case 2: //secondary skill
  453. bonus->type = Bonus::SECONDARY_SKILL_PREMY;
  454. bonus->valType = Bonus::PERCENT_TO_BASE;
  455. bonus->subtype = spec.subtype;
  456. bonus->updater.reset(new TimesHeroLevelUpdater());
  457. result.push_back(bonus);
  458. break;
  459. case 3: //spell damage bonus, level dependent but calculated elsewhere
  460. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  461. bonus->subtype = spec.subtype;
  462. bonus->updater.reset(new TimesHeroLevelUpdater());
  463. result.push_back(bonus);
  464. break;
  465. case 4: //creature stat boost
  466. switch (spec.subtype)
  467. {
  468. case 1:
  469. bonus->type = Bonus::PRIMARY_SKILL;
  470. bonus->subtype = PrimarySkill::ATTACK;
  471. break;
  472. case 2:
  473. bonus->type = Bonus::PRIMARY_SKILL;
  474. bonus->subtype = PrimarySkill::DEFENSE;
  475. break;
  476. case 3:
  477. bonus->type = Bonus::CREATURE_DAMAGE;
  478. bonus->subtype = 0; //both min and max
  479. break;
  480. case 4:
  481. bonus->type = Bonus::STACK_HEALTH;
  482. break;
  483. case 5:
  484. bonus->type = Bonus::STACKS_SPEED;
  485. break;
  486. default:
  487. logMod->warn("Unknown subtype for specialty 4");
  488. return result;
  489. }
  490. bonus->valType = Bonus::ADDITIVE_VALUE;
  491. bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->objects[spec.additionalinfo], true));
  492. result.push_back(bonus);
  493. break;
  494. case 5: //spell damage bonus in percent
  495. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  496. bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
  497. bonus->subtype = spec.subtype; //spell id
  498. result.push_back(bonus);
  499. break;
  500. case 6: //damage bonus for bless (Adela)
  501. {
  502. auto limiter = std::make_shared<HasAnotherBonusLimiter>(Bonus::GENERAL_DAMAGE_PREMY,Bonus::SPELL_EFFECT);
  503. limiter->sid = spec.subtype; //spell id if you ever wanted to use it otherwise
  504. limiter->isSourceIDRelevant = true;
  505. bonus->type = Bonus::GENERAL_DAMAGE_PREMY;
  506. bonus->updater.reset(new TimesHeroLevelUpdater());
  507. bonus->addLimiter(limiter);
  508. result.push_back(bonus);
  509. break;
  510. }
  511. case 7: //maxed mastery for spell
  512. bonus->type = Bonus::SPELL;
  513. bonus->subtype = spec.subtype; //spell id
  514. bonus->val = 3; //to match MAXED_SPELL
  515. bonus->valType = Bonus::INDEPENDENT_MAX;
  516. result.push_back(bonus);
  517. break;
  518. case 8: //peculiar spells - enchantments
  519. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  520. bonus->subtype = spec.subtype; //spell id
  521. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  522. result.push_back(bonus);
  523. break;
  524. case 9: //upgrade creatures
  525. {
  526. const auto &creatures = VLC->creh->objects;
  527. bonus->type = Bonus::SPECIAL_UPGRADE;
  528. bonus->subtype = spec.subtype; //base id
  529. bonus->additionalInfo = spec.additionalinfo; //target id
  530. result.push_back(bonus);
  531. //propagate for regular upgrades of base creature
  532. for(auto cre_id : creatures[spec.subtype]->upgrades)
  533. {
  534. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  535. upgradeUpgradedVersion->subtype = cre_id;
  536. result.push_back(upgradeUpgradedVersion);
  537. }
  538. }
  539. break;
  540. case 10: //resource generation
  541. bonus->type = Bonus::GENERATE_RESOURCE;
  542. bonus->subtype = spec.subtype;
  543. result.push_back(bonus);
  544. break;
  545. case 11: //starting skill with mastery (Adrienne)
  546. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  547. break;
  548. case 12: //army speed
  549. bonus->type = Bonus::STACKS_SPEED;
  550. result.push_back(bonus);
  551. break;
  552. case 13: //Dragon bonuses (Mutare)
  553. bonus->type = Bonus::PRIMARY_SKILL;
  554. bonus->valType = Bonus::ADDITIVE_VALUE;
  555. switch(spec.subtype)
  556. {
  557. case 1:
  558. bonus->subtype = PrimarySkill::ATTACK;
  559. break;
  560. case 2:
  561. bonus->subtype = PrimarySkill::DEFENSE;
  562. break;
  563. }
  564. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  565. result.push_back(bonus);
  566. break;
  567. default:
  568. logMod->warn("Unknown hero specialty %d", spec.type);
  569. break;
  570. }
  571. return result;
  572. }
  573. void CHeroHandler::beforeValidate(JsonNode & object)
  574. {
  575. //handle "base" specialty info
  576. JsonNode & specialtyNode = object["specialty"];
  577. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  578. {
  579. const JsonNode & base = specialtyNode["base"];
  580. if(!base.isNull())
  581. {
  582. if(specialtyNode["bonuses"].isNull())
  583. {
  584. logMod->warn("specialty has base without bonuses");
  585. }
  586. else
  587. {
  588. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  589. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  590. JsonUtils::inherit(bonuses[keyValue.first], base);
  591. }
  592. }
  593. }
  594. }
  595. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  596. {
  597. int sid = hero->ID.getNum();
  598. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  599. {
  600. bonus->duration = Bonus::PERMANENT;
  601. bonus->source = Bonus::HERO_SPECIAL;
  602. bonus->sid = sid;
  603. return bonus;
  604. };
  605. //new format, using bonus system
  606. const JsonNode & specialtyNode = node["specialty"];
  607. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  608. {
  609. //creature specialty - alias for simplicity
  610. if(!specialtyNode["creature"].isNull())
  611. {
  612. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  613. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  614. SSpecialtyInfo spec;
  615. spec.type = 1;
  616. spec.additionalinfo = creature;
  617. hero->specDeprecated.push_back(spec);
  618. });
  619. }
  620. if(!specialtyNode["bonuses"].isNull())
  621. {
  622. //proper new format
  623. for(auto keyValue : specialtyNode["bonuses"].Struct())
  624. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  625. }
  626. }
  627. else
  628. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  629. }
  630. void CHeroHandler::loadExperience()
  631. {
  632. expPerLevel.push_back(0);
  633. expPerLevel.push_back(1000);
  634. expPerLevel.push_back(2000);
  635. expPerLevel.push_back(3200);
  636. expPerLevel.push_back(4600);
  637. expPerLevel.push_back(6200);
  638. expPerLevel.push_back(8000);
  639. expPerLevel.push_back(10000);
  640. expPerLevel.push_back(12200);
  641. expPerLevel.push_back(14700);
  642. expPerLevel.push_back(17500);
  643. expPerLevel.push_back(20600);
  644. expPerLevel.push_back(24320);
  645. expPerLevel.push_back(28784);
  646. expPerLevel.push_back(34140);
  647. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  648. {
  649. auto i = expPerLevel.size() - 1;
  650. auto diff = expPerLevel[i] - expPerLevel[i-1];
  651. diff += diff / 5;
  652. expPerLevel.push_back (expPerLevel[i] + diff);
  653. }
  654. expPerLevel.pop_back();//last value is broken
  655. }
  656. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  657. static std::string genRefName(std::string input)
  658. {
  659. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  660. input[0] = std::tolower(input[0]); // to camelCase
  661. return input;
  662. }
  663. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  664. {
  665. objects.resize(dataSize);
  666. std::vector<JsonNode> h3Data;
  667. h3Data.reserve(dataSize);
  668. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  669. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  670. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  671. parser.endLine(); //ignore header
  672. parser.endLine();
  673. specParser.endLine(); //ignore header
  674. specParser.endLine();
  675. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  676. {
  677. JsonNode heroData;
  678. heroData["texts"]["name"].String() = parser.readString();
  679. heroData["texts"]["biography"].String() = bioParser.readString();
  680. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  681. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  682. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  683. for(int x=0;x<3;x++)
  684. {
  685. JsonNode armySlot;
  686. armySlot["min"].Float() = parser.readNumber();
  687. armySlot["max"].Float() = parser.readNumber();
  688. armySlot["creature"].String() = genRefName(parser.readString());
  689. heroData["army"].Vector().push_back(armySlot);
  690. }
  691. parser.endLine();
  692. specParser.endLine();
  693. bioParser.endLine();
  694. h3Data.push_back(heroData);
  695. }
  696. return h3Data;
  697. }
  698. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  699. {
  700. size_t index = objects.size();
  701. auto object = loadFromJson(scope, data, name, index);
  702. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  703. objects.push_back(object);
  704. registerObject(scope, "hero", name, object->getIndex());
  705. }
  706. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  707. {
  708. auto object = loadFromJson(scope, data, name, index);
  709. object->imageIndex = static_cast<si32>(index);
  710. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  711. objects[index] = object;
  712. registerObject(scope, "hero", name, object->getIndex());
  713. }
  714. void CHeroHandler::afterLoadFinalization()
  715. {
  716. for(auto & hero : objects)
  717. {
  718. for(auto bonus : hero->specialty)
  719. {
  720. bonus->sid = hero->getIndex();
  721. }
  722. if(hero->specDeprecated.size() > 0)
  723. {
  724. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  725. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  726. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  727. {
  728. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  729. convertedBonuses.push_back(b);
  730. }
  731. hero->specDeprecated.clear();
  732. // store and create json for logging
  733. std::vector<JsonNode> specVec;
  734. std::vector<std::string> specNames;
  735. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  736. {
  737. hero->specialty.push_back(bonus);
  738. specVec.push_back(bonus->toJsonNode());
  739. // find fitting & unique bonus name
  740. std::string bonusName = bonus->nameForBonus();
  741. if(vstd::contains(specNames, bonusName))
  742. {
  743. int suffix = 2;
  744. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  745. suffix++;
  746. bonusName += std::to_string(suffix);
  747. }
  748. specNames.push_back(bonusName);
  749. }
  750. // log new format for easy copy-and-paste
  751. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  752. if(specVec.size() > 1)
  753. {
  754. JsonNode base = JsonUtils::intersect(specVec);
  755. if(base.containsBaseData())
  756. {
  757. specNode["base"] = base;
  758. for(JsonNode & node : specVec)
  759. node = JsonUtils::difference(node, base);
  760. }
  761. }
  762. // add json for bonuses
  763. specNode["bonuses"].Struct();
  764. for(int i = 0; i < specVec.size(); i++)
  765. specNode["bonuses"][specNames[i]] = specVec[i];
  766. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  767. }
  768. }
  769. }
  770. ui32 CHeroHandler::level (ui64 experience) const
  771. {
  772. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  773. }
  774. ui64 CHeroHandler::reqExp (ui32 level) const
  775. {
  776. if(!level)
  777. return 0;
  778. if (level <= expPerLevel.size())
  779. {
  780. return expPerLevel[level-1];
  781. }
  782. else
  783. {
  784. logGlobal->warn("A hero has reached unsupported amount of experience");
  785. return expPerLevel[expPerLevel.size()-1];
  786. }
  787. }
  788. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  789. {
  790. // Look Data/HOTRAITS.txt for reference
  791. std::vector<bool> allowedHeroes;
  792. allowedHeroes.reserve(size());
  793. for(const CHero * hero : objects)
  794. {
  795. allowedHeroes.push_back(!hero->special);
  796. }
  797. return allowedHeroes;
  798. }
  799. VCMI_LIB_NAMESPACE_END