CHeroHandler.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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. const std::string & CHero::getName() const
  38. {
  39. return identifier;
  40. }
  41. const std::string & CHero::getJsonKey() const
  42. {
  43. return identifier;
  44. }
  45. HeroTypeID CHero::getId() const
  46. {
  47. return ID;
  48. }
  49. std::string CHero::getNameTranslated() const
  50. {
  51. return VLC->generaltexth->translate(getNameTextID());
  52. }
  53. std::string CHero::getBiographyTranslated() const
  54. {
  55. return VLC->generaltexth->translate(getBiographyTextID());
  56. }
  57. std::string CHero::getSpecialtyNameTranslated() const
  58. {
  59. return VLC->generaltexth->translate(getSpecialtyNameTextID());
  60. }
  61. std::string CHero::getSpecialtyDescriptionTranslated() const
  62. {
  63. return VLC->generaltexth->translate(getSpecialtyDescriptionTextID());
  64. }
  65. std::string CHero::getSpecialtyTooltipTranslated() const
  66. {
  67. return VLC->generaltexth->translate(getSpecialtyTooltipTextID());
  68. }
  69. std::string CHero::getNameTextID() const
  70. {
  71. return TextIdentifier("hero", modScope, identifier, "name").get();
  72. }
  73. std::string CHero::getBiographyTextID() const
  74. {
  75. return TextIdentifier("hero", modScope, identifier, "biography").get();
  76. }
  77. std::string CHero::getSpecialtyNameTextID() const
  78. {
  79. return TextIdentifier("hero", modScope, identifier, "specialty", "name").get();
  80. }
  81. std::string CHero::getSpecialtyDescriptionTextID() const
  82. {
  83. return TextIdentifier("hero", modScope, identifier, "specialty", "description").get();
  84. }
  85. std::string CHero::getSpecialtyTooltipTextID() const
  86. {
  87. return TextIdentifier("hero", modScope, identifier, "specialty", "tooltip").get();
  88. }
  89. void CHero::registerIcons(const IconRegistar & cb) const
  90. {
  91. cb(getIconIndex(), 0, "UN32", iconSpecSmall);
  92. cb(getIconIndex(), 0, "UN44", iconSpecLarge);
  93. cb(getIconIndex(), 0, "PORTRAITSLARGE", portraitLarge);
  94. cb(getIconIndex(), 0, "PORTRAITSSMALL", portraitSmall);
  95. }
  96. void CHero::updateFrom(const JsonNode & data)
  97. {
  98. //todo: CHero::updateFrom
  99. }
  100. void CHero::serializeJson(JsonSerializeFormat & handler)
  101. {
  102. }
  103. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  104. {
  105. int totalProb = 0;
  106. for(auto & possible : possibles)
  107. {
  108. totalProb += secSkillProbability[possible];
  109. }
  110. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  111. {
  112. auto ran = rand.nextInt(totalProb - 1);
  113. for(auto & possible : possibles)
  114. {
  115. ran -= secSkillProbability[possible];
  116. if(ran < 0)
  117. {
  118. return possible;
  119. }
  120. }
  121. }
  122. // FIXME: select randomly? How H3 handles such rare situation?
  123. return *possibles.begin();
  124. }
  125. bool CHeroClass::isMagicHero() const
  126. {
  127. return affinity == MAGIC;
  128. }
  129. EAlignment::EAlignment CHeroClass::getAlignment() const
  130. {
  131. return EAlignment::EAlignment((*VLC->townh)[faction]->alignment);
  132. }
  133. int32_t CHeroClass::getIndex() const
  134. {
  135. return id.getNum();
  136. }
  137. int32_t CHeroClass::getIconIndex() const
  138. {
  139. return getIndex();
  140. }
  141. const std::string & CHeroClass::getName() const
  142. {
  143. return identifier;
  144. }
  145. const std::string & CHeroClass::getJsonKey() const
  146. {
  147. return identifier;
  148. }
  149. HeroClassID CHeroClass::getId() const
  150. {
  151. return id;
  152. }
  153. void CHeroClass::registerIcons(const IconRegistar & cb) const
  154. {
  155. }
  156. std::string CHeroClass::getNameTranslated() const
  157. {
  158. return VLC->generaltexth->translate(getNameTextID());
  159. }
  160. std::string CHeroClass::getNameTextID() const
  161. {
  162. return TextIdentifier("heroClass", modScope, identifier, "specialty", "name").get();
  163. }
  164. void CHeroClass::updateFrom(const JsonNode & data)
  165. {
  166. //TODO: CHeroClass::updateFrom
  167. }
  168. void CHeroClass::serializeJson(JsonSerializeFormat & handler)
  169. {
  170. }
  171. CHeroClass::CHeroClass()
  172. : faction(0), id(), affinity(0), defaultTavernChance(0), commander(nullptr)
  173. {
  174. }
  175. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill::PrimarySkill pSkill)
  176. {
  177. const auto & skillName = PrimarySkill::names[pSkill];
  178. auto currentPrimarySkillValue = (int)node["primarySkills"][skillName].Integer();
  179. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  180. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  181. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  182. {
  183. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  184. heroClass->getName(), currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  185. currentPrimarySkillValue = primarySkillLegalMinimum;
  186. }
  187. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  188. heroClass->primarySkillLowLevel.push_back((int)node["lowLevelChance"][skillName].Float());
  189. heroClass->primarySkillHighLevel.push_back((int)node["highLevelChance"][skillName].Float());
  190. }
  191. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  192. {
  193. static const std::vector<std::string> typeNames = { "heroClass" };
  194. return typeNames;
  195. }
  196. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  197. {
  198. std::string affinityStr[2] = { "might", "magic" };
  199. auto heroClass = new CHeroClass();
  200. heroClass->id = HeroClassID(index);
  201. heroClass->identifier = identifier;
  202. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  203. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  204. //MODS COMPATIBILITY FOR 0.96
  205. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  206. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  207. VLC->generaltexth->registerString( heroClass->getNameTextID(), node["name"].String());
  208. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  209. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  210. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  211. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  212. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  213. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  214. if(percentSumm != 100)
  215. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  216. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  217. if(percentSumm != 100)
  218. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  219. for(auto skillPair : node["secondarySkills"].Struct())
  220. {
  221. int probability = static_cast<int>(skillPair.second.Integer());
  222. VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  223. {
  224. if(heroClass->secSkillProbability.size() <= skillID)
  225. heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
  226. heroClass->secSkillProbability[skillID] = probability;
  227. });
  228. }
  229. VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
  230. [=](si32 commanderID)
  231. {
  232. heroClass->commander = VLC->creh->objects[commanderID];
  233. });
  234. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  235. for(auto & tavern : node["tavern"].Struct())
  236. {
  237. int value = static_cast<int>(tavern.second.Float());
  238. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  239. [=](si32 factionID)
  240. {
  241. heroClass->selectionProbability[factionID] = value;
  242. });
  243. }
  244. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  245. [=](si32 factionID)
  246. {
  247. heroClass->faction = factionID;
  248. });
  249. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  250. {
  251. JsonNode classConf = node["mapObject"];
  252. classConf["heroClass"].String() = identifier;
  253. classConf.setMeta(scope);
  254. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  255. });
  256. return heroClass;
  257. }
  258. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  259. {
  260. objects.resize(dataSize);
  261. std::vector<JsonNode> h3Data;
  262. h3Data.reserve(dataSize);
  263. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  264. parser.endLine(); // header
  265. parser.endLine();
  266. for (size_t i=0; i<dataSize; i++)
  267. {
  268. JsonNode entry;
  269. entry["name"].String() = parser.readString();
  270. parser.readNumber(); // unused aggression
  271. for (auto & name : PrimarySkill::names)
  272. entry["primarySkills"][name].Float() = parser.readNumber();
  273. for (auto & name : PrimarySkill::names)
  274. entry["lowLevelChance"][name].Float() = parser.readNumber();
  275. for (auto & name : PrimarySkill::names)
  276. entry["highLevelChance"][name].Float() = parser.readNumber();
  277. for (auto & name : NSecondarySkill::names)
  278. entry["secondarySkills"][name].Float() = parser.readNumber();
  279. for(auto & name : ETownType::names)
  280. entry["tavern"][name].Float() = parser.readNumber();
  281. parser.endLine();
  282. h3Data.push_back(entry);
  283. }
  284. return h3Data;
  285. }
  286. void CHeroClassHandler::afterLoadFinalization()
  287. {
  288. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  289. for(CHeroClass * heroClass : objects)
  290. {
  291. for(CFaction * faction : VLC->townh->objects)
  292. {
  293. if (!faction->town)
  294. continue;
  295. if (heroClass->selectionProbability.count(faction->getIndex()))
  296. continue;
  297. float chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  298. heroClass->selectionProbability[faction->getIndex()] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  299. }
  300. // set default probabilities for gaining secondary skills where not loaded previously
  301. heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
  302. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  303. {
  304. if(heroClass->secSkillProbability[skillID] < 0)
  305. {
  306. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  307. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->getJsonKey());
  308. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  309. }
  310. }
  311. }
  312. for(CHeroClass * hc : objects)
  313. {
  314. if (!hc->imageMapMale.empty())
  315. {
  316. JsonNode templ;
  317. templ["animation"].String() = hc->imageMapMale;
  318. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  319. }
  320. }
  321. }
  322. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  323. {
  324. return std::vector<bool>(size(), true);
  325. }
  326. CHeroClassHandler::~CHeroClassHandler() = default;
  327. CHeroHandler::~CHeroHandler() = default;
  328. CHeroHandler::CHeroHandler()
  329. {
  330. loadBallistics();
  331. loadExperience();
  332. }
  333. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  334. {
  335. static const std::vector<std::string> typeNames = { "hero" };
  336. return typeNames;
  337. }
  338. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  339. {
  340. auto hero = new CHero();
  341. hero->ID = HeroTypeID(index);
  342. hero->identifier = identifier;
  343. hero->sex = node["female"].Bool();
  344. hero->special = node["special"].Bool();
  345. VLC->generaltexth->registerString( hero->getNameTextID(), node["texts"]["name"].String());
  346. VLC->generaltexth->registerString( hero->getBiographyTextID(), node["texts"]["biography"].String());
  347. VLC->generaltexth->registerString( hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  348. VLC->generaltexth->registerString( hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  349. VLC->generaltexth->registerString( hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"].String());
  350. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  351. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  352. hero->portraitSmall = node["images"]["small"].String();
  353. hero->portraitLarge = node["images"]["large"].String();
  354. hero->battleImage = node["battleImage"].String();
  355. loadHeroArmy(hero, node);
  356. loadHeroSkills(hero, node);
  357. loadHeroSpecialty(hero, node);
  358. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  359. [=](si32 classID)
  360. {
  361. hero->heroClass = classes[HeroClassID(classID)];
  362. });
  363. return hero;
  364. }
  365. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  366. {
  367. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  368. hero->initialArmy.resize(node["army"].Vector().size());
  369. for (size_t i=0; i< hero->initialArmy.size(); i++)
  370. {
  371. const JsonNode & source = node["army"].Vector()[i];
  372. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  373. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  374. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  375. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  376. {
  377. hero->initialArmy[i].creature = CreatureID(creature);
  378. });
  379. }
  380. }
  381. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  382. {
  383. for(const JsonNode &set : node["skills"].Vector())
  384. {
  385. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  386. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  387. {
  388. size_t currentIndex = hero->secSkillsInit.size();
  389. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  390. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  391. {
  392. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  393. });
  394. }
  395. else
  396. {
  397. logMod->error("Unknown skill level: %s", set["level"].String());
  398. }
  399. }
  400. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  401. hero->haveSpellBook = !node["spellbook"].isNull();
  402. for(const JsonNode & spell : node["spellbook"].Vector())
  403. {
  404. VLC->modh->identifiers.requestIdentifier("spell", spell,
  405. [=](si32 spellID)
  406. {
  407. hero->spells.insert(SpellID(spellID));
  408. });
  409. }
  410. }
  411. // add standard creature specialty to result
  412. void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
  413. {
  414. const CCreature &specBaseCreature = *VLC->creh->objects[creatureID]; //base creature in which we have specialty
  415. bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
  416. bonus->type = Bonus::STACKS_SPEED;
  417. bonus->valType = Bonus::ADDITIVE_VALUE;
  418. bonus->val = 1;
  419. result.push_back(bonus);
  420. // attack and defense may differ for upgraded creatures => separate bonuses
  421. std::vector<int> specTargets;
  422. specTargets.push_back(creatureID);
  423. specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());
  424. for(int cid : specTargets)
  425. {
  426. const CCreature &specCreature = *VLC->creh->objects[cid];
  427. bonus = std::make_shared<Bonus>(*bonus);
  428. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  429. bonus->type = Bonus::PRIMARY_SKILL;
  430. bonus->val = 0;
  431. int stepSize = specCreature.level ? specCreature.level : 5;
  432. bonus->subtype = PrimarySkill::ATTACK;
  433. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  434. result.push_back(bonus);
  435. bonus = std::make_shared<Bonus>(*bonus);
  436. bonus->subtype = PrimarySkill::DEFENSE;
  437. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  438. result.push_back(bonus);
  439. }
  440. }
  441. // convert deprecated format
  442. std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
  443. {
  444. std::vector<std::shared_ptr<Bonus>> result;
  445. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  446. bonus->duration = Bonus::PERMANENT;
  447. bonus->source = Bonus::HERO_SPECIAL;
  448. bonus->sid = sid;
  449. bonus->val = spec.val;
  450. switch (spec.type)
  451. {
  452. case 1: //creature specialty
  453. AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
  454. break;
  455. case 2: //secondary skill
  456. bonus->type = Bonus::SECONDARY_SKILL_PREMY;
  457. bonus->valType = Bonus::PERCENT_TO_BASE;
  458. bonus->subtype = spec.subtype;
  459. bonus->updater.reset(new TimesHeroLevelUpdater());
  460. result.push_back(bonus);
  461. break;
  462. case 3: //spell damage bonus, level dependent but calculated elsewhere
  463. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  464. bonus->subtype = spec.subtype;
  465. bonus->updater.reset(new TimesHeroLevelUpdater());
  466. result.push_back(bonus);
  467. break;
  468. case 4: //creature stat boost
  469. switch (spec.subtype)
  470. {
  471. case 1:
  472. bonus->type = Bonus::PRIMARY_SKILL;
  473. bonus->subtype = PrimarySkill::ATTACK;
  474. break;
  475. case 2:
  476. bonus->type = Bonus::PRIMARY_SKILL;
  477. bonus->subtype = PrimarySkill::DEFENSE;
  478. break;
  479. case 3:
  480. bonus->type = Bonus::CREATURE_DAMAGE;
  481. bonus->subtype = 0; //both min and max
  482. break;
  483. case 4:
  484. bonus->type = Bonus::STACK_HEALTH;
  485. break;
  486. case 5:
  487. bonus->type = Bonus::STACKS_SPEED;
  488. break;
  489. default:
  490. logMod->warn("Unknown subtype for specialty 4");
  491. return result;
  492. }
  493. bonus->valType = Bonus::ADDITIVE_VALUE;
  494. bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->objects[spec.additionalinfo], true));
  495. result.push_back(bonus);
  496. break;
  497. case 5: //spell damage bonus in percent
  498. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  499. bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
  500. bonus->subtype = spec.subtype; //spell id
  501. result.push_back(bonus);
  502. break;
  503. case 6: //damage bonus for bless (Adela)
  504. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  505. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  506. bonus->additionalInfo = spec.additionalinfo; //damage factor
  507. bonus->updater.reset(new TimesHeroLevelUpdater());
  508. result.push_back(bonus);
  509. break;
  510. case 7: //maxed mastery for spell
  511. bonus->type = Bonus::MAXED_SPELL;
  512. bonus->subtype = spec.subtype; //spell id
  513. result.push_back(bonus);
  514. break;
  515. case 8: //peculiar spells - enchantments
  516. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  517. bonus->subtype = spec.subtype; //spell id
  518. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  519. result.push_back(bonus);
  520. break;
  521. case 9: //upgrade creatures
  522. {
  523. const auto &creatures = VLC->creh->objects;
  524. bonus->type = Bonus::SPECIAL_UPGRADE;
  525. bonus->subtype = spec.subtype; //base id
  526. bonus->additionalInfo = spec.additionalinfo; //target id
  527. result.push_back(bonus);
  528. //propagate for regular upgrades of base creature
  529. for(auto cre_id : creatures[spec.subtype]->upgrades)
  530. {
  531. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  532. upgradeUpgradedVersion->subtype = cre_id;
  533. result.push_back(upgradeUpgradedVersion);
  534. }
  535. }
  536. break;
  537. case 10: //resource generation
  538. bonus->type = Bonus::GENERATE_RESOURCE;
  539. bonus->subtype = spec.subtype;
  540. result.push_back(bonus);
  541. break;
  542. case 11: //starting skill with mastery (Adrienne)
  543. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  544. break;
  545. case 12: //army speed
  546. bonus->type = Bonus::STACKS_SPEED;
  547. result.push_back(bonus);
  548. break;
  549. case 13: //Dragon bonuses (Mutare)
  550. bonus->type = Bonus::PRIMARY_SKILL;
  551. bonus->valType = Bonus::ADDITIVE_VALUE;
  552. switch(spec.subtype)
  553. {
  554. case 1:
  555. bonus->subtype = PrimarySkill::ATTACK;
  556. break;
  557. case 2:
  558. bonus->subtype = PrimarySkill::DEFENSE;
  559. break;
  560. }
  561. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  562. result.push_back(bonus);
  563. break;
  564. default:
  565. logMod->warn("Unknown hero specialty %d", spec.type);
  566. break;
  567. }
  568. return result;
  569. }
  570. // convert deprecated format
  571. std::vector<std::shared_ptr<Bonus>> SpecialtyBonusToBonuses(const SSpecialtyBonus & spec, int sid)
  572. {
  573. std::vector<std::shared_ptr<Bonus>> result;
  574. for(std::shared_ptr<Bonus> oldBonus : spec.bonuses)
  575. {
  576. oldBonus->sid = sid;
  577. if(oldBonus->type == Bonus::SPECIAL_SPELL_LEV || oldBonus->type == Bonus::SPECIAL_BLESS_DAMAGE)
  578. {
  579. // these bonuses used to auto-scale with hero level
  580. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  581. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  582. result.push_back(newBonus);
  583. }
  584. else if(spec.growsWithLevel)
  585. {
  586. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  587. switch(newBonus->type)
  588. {
  589. case Bonus::SECONDARY_SKILL_PREMY:
  590. break; // ignore - used to be overwritten based on SPECIAL_SECONDARY_SKILL
  591. case Bonus::SPECIAL_SECONDARY_SKILL:
  592. newBonus->type = Bonus::SECONDARY_SKILL_PREMY;
  593. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  594. result.push_back(newBonus);
  595. break;
  596. case Bonus::PRIMARY_SKILL:
  597. if((newBonus->subtype == PrimarySkill::ATTACK || newBonus->subtype == PrimarySkill::DEFENSE) && newBonus->limiter)
  598. {
  599. std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(newBonus->limiter);
  600. if(creatureLimiter)
  601. {
  602. const CCreature * cre = creatureLimiter->creature;
  603. int creStat = newBonus->subtype == PrimarySkill::ATTACK ? cre->getAttack(false) : cre->getDefense(false);
  604. int creLevel = cre->level ? cre->level : 5;
  605. newBonus->updater = std::make_shared<GrowsWithLevelUpdater>(creStat, creLevel);
  606. }
  607. result.push_back(newBonus);
  608. }
  609. break;
  610. default:
  611. result.push_back(newBonus);
  612. }
  613. }
  614. else
  615. {
  616. result.push_back(oldBonus);
  617. }
  618. }
  619. return result;
  620. }
  621. void CHeroHandler::beforeValidate(JsonNode & object)
  622. {
  623. //handle "base" specialty info
  624. JsonNode & specialtyNode = object["specialty"];
  625. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  626. {
  627. const JsonNode & base = specialtyNode["base"];
  628. if(!base.isNull())
  629. {
  630. if(specialtyNode["bonuses"].isNull())
  631. {
  632. logMod->warn("specialty has base without bonuses");
  633. }
  634. else
  635. {
  636. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  637. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  638. JsonUtils::inherit(bonuses[keyValue.first], base);
  639. }
  640. }
  641. }
  642. }
  643. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  644. {
  645. int sid = hero->ID.getNum();
  646. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  647. {
  648. bonus->duration = Bonus::PERMANENT;
  649. bonus->source = Bonus::HERO_SPECIAL;
  650. bonus->sid = sid;
  651. return bonus;
  652. };
  653. //deprecated, used only for original specialties
  654. const JsonNode & specialtiesNode = node["specialties"];
  655. if (!specialtiesNode.isNull())
  656. {
  657. logMod->warn("Hero %s has deprecated specialties format.", hero->getNameTranslated());
  658. for(const JsonNode &specialty : specialtiesNode.Vector())
  659. {
  660. SSpecialtyInfo spec;
  661. spec.type = static_cast<si32>(specialty["type"].Integer());
  662. spec.val = static_cast<si32>(specialty["val"].Integer());
  663. spec.subtype = static_cast<si32>(specialty["subtype"].Integer());
  664. spec.additionalinfo = static_cast<si32>(specialty["info"].Integer());
  665. //we convert after loading completes, to have all identifiers for json logging
  666. hero->specDeprecated.push_back(spec);
  667. }
  668. }
  669. //new(er) format, using bonus system
  670. const JsonNode & specialtyNode = node["specialty"];
  671. if(specialtyNode.getType() == JsonNode::JsonType::DATA_VECTOR)
  672. {
  673. //deprecated middle-aged format
  674. for(const JsonNode & specialty : node["specialty"].Vector())
  675. {
  676. SSpecialtyBonus hs;
  677. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  678. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  679. hs.bonuses.push_back(prepSpec(JsonUtils::parseBonus(bonus)));
  680. hero->specialtyDeprecated.push_back(hs);
  681. }
  682. }
  683. else if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  684. {
  685. //creature specialty - alias for simplicity
  686. if(!specialtyNode["creature"].isNull())
  687. {
  688. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  689. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  690. SSpecialtyInfo spec;
  691. spec.type = 1;
  692. spec.additionalinfo = creature;
  693. hero->specDeprecated.push_back(spec);
  694. });
  695. }
  696. if(!specialtyNode["bonuses"].isNull())
  697. {
  698. //proper new format
  699. for(auto keyValue : specialtyNode["bonuses"].Struct())
  700. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  701. }
  702. }
  703. }
  704. void CHeroHandler::loadExperience()
  705. {
  706. expPerLevel.push_back(0);
  707. expPerLevel.push_back(1000);
  708. expPerLevel.push_back(2000);
  709. expPerLevel.push_back(3200);
  710. expPerLevel.push_back(4600);
  711. expPerLevel.push_back(6200);
  712. expPerLevel.push_back(8000);
  713. expPerLevel.push_back(10000);
  714. expPerLevel.push_back(12200);
  715. expPerLevel.push_back(14700);
  716. expPerLevel.push_back(17500);
  717. expPerLevel.push_back(20600);
  718. expPerLevel.push_back(24320);
  719. expPerLevel.push_back(28784);
  720. expPerLevel.push_back(34140);
  721. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  722. {
  723. auto i = expPerLevel.size() - 1;
  724. auto diff = expPerLevel[i] - expPerLevel[i-1];
  725. diff += diff / 5;
  726. expPerLevel.push_back (expPerLevel[i] + diff);
  727. }
  728. expPerLevel.pop_back();//last value is broken
  729. }
  730. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  731. static std::string genRefName(std::string input)
  732. {
  733. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  734. input[0] = std::tolower(input[0]); // to camelCase
  735. return input;
  736. }
  737. void CHeroHandler::loadBallistics()
  738. {
  739. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  740. ballParser.endLine(); //header
  741. ballParser.endLine();
  742. do
  743. {
  744. ballParser.readString();
  745. ballParser.readString();
  746. CHeroHandler::SBallisticsLevelInfo bli;
  747. bli.keep = static_cast<ui8>(ballParser.readNumber());
  748. bli.tower = static_cast<ui8>(ballParser.readNumber());
  749. bli.gate = static_cast<ui8>(ballParser.readNumber());
  750. bli.wall = static_cast<ui8>(ballParser.readNumber());
  751. bli.shots = static_cast<ui8>(ballParser.readNumber());
  752. bli.noDmg = static_cast<ui8>(ballParser.readNumber());
  753. bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
  754. bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
  755. bli.sum = static_cast<ui8>(ballParser.readNumber());
  756. ballistics.push_back(bli);
  757. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  758. }
  759. while (ballParser.endLine());
  760. }
  761. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  762. {
  763. objects.resize(dataSize);
  764. std::vector<JsonNode> h3Data;
  765. h3Data.reserve(dataSize);
  766. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  767. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  768. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  769. parser.endLine(); //ignore header
  770. parser.endLine();
  771. specParser.endLine(); //ignore header
  772. specParser.endLine();
  773. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  774. {
  775. JsonNode heroData;
  776. heroData["texts"]["name"].String() = parser.readString();
  777. heroData["texts"]["biography"].String() = bioParser.readString();
  778. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  779. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  780. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  781. for(int x=0;x<3;x++)
  782. {
  783. JsonNode armySlot;
  784. armySlot["min"].Float() = parser.readNumber();
  785. armySlot["max"].Float() = parser.readNumber();
  786. armySlot["creature"].String() = genRefName(parser.readString());
  787. heroData["army"].Vector().push_back(armySlot);
  788. }
  789. parser.endLine();
  790. specParser.endLine();
  791. bioParser.endLine();
  792. h3Data.push_back(heroData);
  793. }
  794. return h3Data;
  795. }
  796. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  797. {
  798. size_t index = objects.size();
  799. auto object = loadFromJson(scope, data, normalizeIdentifier(scope, CModHandler::scopeBuiltin(), name), index);
  800. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  801. objects.push_back(object);
  802. registerObject(scope, "hero", name, object->getIndex());
  803. }
  804. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  805. {
  806. auto object = loadFromJson(scope, data, normalizeIdentifier(scope, CModHandler::scopeBuiltin(), name), index);
  807. object->imageIndex = static_cast<si32>(index);
  808. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  809. objects[index] = object;
  810. registerObject(scope, "hero", name, object->getIndex());
  811. }
  812. void CHeroHandler::afterLoadFinalization()
  813. {
  814. for(auto & hero : objects)
  815. {
  816. for(auto bonus : hero->specialty)
  817. {
  818. bonus->sid = hero->getIndex();
  819. }
  820. if(hero->specDeprecated.size() > 0 || hero->specialtyDeprecated.size() > 0)
  821. {
  822. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  823. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  824. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  825. {
  826. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  827. convertedBonuses.push_back(b);
  828. }
  829. for(const SSpecialtyBonus & spec : hero->specialtyDeprecated)
  830. {
  831. for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(spec, hero->ID.getNum()))
  832. convertedBonuses.push_back(b);
  833. }
  834. hero->specDeprecated.clear();
  835. hero->specialtyDeprecated.clear();
  836. // store and create json for logging
  837. std::vector<JsonNode> specVec;
  838. std::vector<std::string> specNames;
  839. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  840. {
  841. hero->specialty.push_back(bonus);
  842. specVec.push_back(bonus->toJsonNode());
  843. // find fitting & unique bonus name
  844. std::string bonusName = bonus->nameForBonus();
  845. if(vstd::contains(specNames, bonusName))
  846. {
  847. int suffix = 2;
  848. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  849. suffix++;
  850. bonusName += std::to_string(suffix);
  851. }
  852. specNames.push_back(bonusName);
  853. }
  854. // log new format for easy copy-and-paste
  855. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  856. if(specVec.size() > 1)
  857. {
  858. JsonNode base = JsonUtils::intersect(specVec);
  859. if(base.containsBaseData())
  860. {
  861. specNode["base"] = base;
  862. for(JsonNode & node : specVec)
  863. node = JsonUtils::difference(node, base);
  864. }
  865. }
  866. // add json for bonuses
  867. specNode["bonuses"].Struct();
  868. for(int i = 0; i < specVec.size(); i++)
  869. specNode["bonuses"][specNames[i]] = specVec[i];
  870. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  871. }
  872. }
  873. }
  874. ui32 CHeroHandler::level (ui64 experience) const
  875. {
  876. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  877. }
  878. ui64 CHeroHandler::reqExp (ui32 level) const
  879. {
  880. if(!level)
  881. return 0;
  882. if (level <= expPerLevel.size())
  883. {
  884. return expPerLevel[level-1];
  885. }
  886. else
  887. {
  888. logGlobal->warn("A hero has reached unsupported amount of experience");
  889. return expPerLevel[expPerLevel.size()-1];
  890. }
  891. }
  892. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  893. {
  894. // Look Data/HOTRAITS.txt for reference
  895. std::vector<bool> allowedHeroes;
  896. allowedHeroes.reserve(size());
  897. for(const CHero * hero : objects)
  898. {
  899. allowedHeroes.push_back(!hero->special);
  900. }
  901. return allowedHeroes;
  902. }
  903. VCMI_LIB_NAMESPACE_END