2
0

CHeroHandler.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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( 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. loadBallistics();
  326. loadExperience();
  327. }
  328. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  329. {
  330. static const std::vector<std::string> typeNames = { "hero" };
  331. return typeNames;
  332. }
  333. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  334. {
  335. assert(identifier.find(':') == std::string::npos);
  336. assert(!scope.empty());
  337. auto hero = new CHero();
  338. hero->ID = HeroTypeID(index);
  339. hero->identifier = identifier;
  340. hero->modScope = scope;
  341. hero->sex = node["female"].Bool();
  342. hero->special = node["special"].Bool();
  343. VLC->generaltexth->registerString( hero->getNameTextID(), node["texts"]["name"].String());
  344. VLC->generaltexth->registerString( hero->getBiographyTextID(), node["texts"]["biography"].String());
  345. VLC->generaltexth->registerString( hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  346. VLC->generaltexth->registerString( hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  347. VLC->generaltexth->registerString( hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"].String());
  348. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  349. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  350. hero->portraitSmall = node["images"]["small"].String();
  351. hero->portraitLarge = node["images"]["large"].String();
  352. hero->battleImage = node["battleImage"].String();
  353. loadHeroArmy(hero, node);
  354. loadHeroSkills(hero, node);
  355. loadHeroSpecialty(hero, node);
  356. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  357. [=](si32 classID)
  358. {
  359. hero->heroClass = classes[HeroClassID(classID)];
  360. });
  361. return hero;
  362. }
  363. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  364. {
  365. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  366. hero->initialArmy.resize(node["army"].Vector().size());
  367. for (size_t i=0; i< hero->initialArmy.size(); i++)
  368. {
  369. const JsonNode & source = node["army"].Vector()[i];
  370. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  371. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  372. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  373. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  374. {
  375. hero->initialArmy[i].creature = CreatureID(creature);
  376. });
  377. }
  378. }
  379. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  380. {
  381. for(const JsonNode &set : node["skills"].Vector())
  382. {
  383. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  384. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  385. {
  386. size_t currentIndex = hero->secSkillsInit.size();
  387. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  388. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  389. {
  390. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  391. });
  392. }
  393. else
  394. {
  395. logMod->error("Unknown skill level: %s", set["level"].String());
  396. }
  397. }
  398. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  399. hero->haveSpellBook = !node["spellbook"].isNull();
  400. for(const JsonNode & spell : node["spellbook"].Vector())
  401. {
  402. VLC->modh->identifiers.requestIdentifier("spell", spell,
  403. [=](si32 spellID)
  404. {
  405. hero->spells.insert(SpellID(spellID));
  406. });
  407. }
  408. }
  409. // add standard creature specialty to result
  410. void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
  411. {
  412. const CCreature &specBaseCreature = *VLC->creh->objects[creatureID]; //base creature in which we have specialty
  413. bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
  414. bonus->type = Bonus::STACKS_SPEED;
  415. bonus->valType = Bonus::ADDITIVE_VALUE;
  416. bonus->val = 1;
  417. result.push_back(bonus);
  418. // attack and defense may differ for upgraded creatures => separate bonuses
  419. std::vector<int> specTargets;
  420. specTargets.push_back(creatureID);
  421. specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());
  422. for(int cid : specTargets)
  423. {
  424. const CCreature &specCreature = *VLC->creh->objects[cid];
  425. bonus = std::make_shared<Bonus>(*bonus);
  426. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  427. bonus->type = Bonus::PRIMARY_SKILL;
  428. bonus->val = 0;
  429. int stepSize = specCreature.level ? specCreature.level : 5;
  430. bonus->subtype = PrimarySkill::ATTACK;
  431. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  432. result.push_back(bonus);
  433. bonus = std::make_shared<Bonus>(*bonus);
  434. bonus->subtype = PrimarySkill::DEFENSE;
  435. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  436. result.push_back(bonus);
  437. }
  438. }
  439. // convert deprecated format
  440. std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
  441. {
  442. std::vector<std::shared_ptr<Bonus>> result;
  443. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  444. bonus->duration = Bonus::PERMANENT;
  445. bonus->source = Bonus::HERO_SPECIAL;
  446. bonus->sid = sid;
  447. bonus->val = spec.val;
  448. switch (spec.type)
  449. {
  450. case 1: //creature specialty
  451. AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
  452. break;
  453. case 2: //secondary skill
  454. bonus->type = Bonus::SECONDARY_SKILL_PREMY;
  455. bonus->valType = Bonus::PERCENT_TO_BASE;
  456. bonus->subtype = spec.subtype;
  457. bonus->updater.reset(new TimesHeroLevelUpdater());
  458. result.push_back(bonus);
  459. break;
  460. case 3: //spell damage bonus, level dependent but calculated elsewhere
  461. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  462. bonus->subtype = spec.subtype;
  463. bonus->updater.reset(new TimesHeroLevelUpdater());
  464. result.push_back(bonus);
  465. break;
  466. case 4: //creature stat boost
  467. switch (spec.subtype)
  468. {
  469. case 1:
  470. bonus->type = Bonus::PRIMARY_SKILL;
  471. bonus->subtype = PrimarySkill::ATTACK;
  472. break;
  473. case 2:
  474. bonus->type = Bonus::PRIMARY_SKILL;
  475. bonus->subtype = PrimarySkill::DEFENSE;
  476. break;
  477. case 3:
  478. bonus->type = Bonus::CREATURE_DAMAGE;
  479. bonus->subtype = 0; //both min and max
  480. break;
  481. case 4:
  482. bonus->type = Bonus::STACK_HEALTH;
  483. break;
  484. case 5:
  485. bonus->type = Bonus::STACKS_SPEED;
  486. break;
  487. default:
  488. logMod->warn("Unknown subtype for specialty 4");
  489. return result;
  490. }
  491. bonus->valType = Bonus::ADDITIVE_VALUE;
  492. bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->objects[spec.additionalinfo], true));
  493. result.push_back(bonus);
  494. break;
  495. case 5: //spell damage bonus in percent
  496. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  497. bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
  498. bonus->subtype = spec.subtype; //spell id
  499. result.push_back(bonus);
  500. break;
  501. case 6: //damage bonus for bless (Adela)
  502. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  503. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  504. bonus->additionalInfo = spec.additionalinfo; //damage factor
  505. bonus->updater.reset(new TimesHeroLevelUpdater());
  506. result.push_back(bonus);
  507. break;
  508. case 7: //maxed mastery for spell
  509. bonus->type = Bonus::MAXED_SPELL;
  510. bonus->subtype = spec.subtype; //spell id
  511. result.push_back(bonus);
  512. break;
  513. case 8: //peculiar spells - enchantments
  514. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  515. bonus->subtype = spec.subtype; //spell id
  516. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  517. result.push_back(bonus);
  518. break;
  519. case 9: //upgrade creatures
  520. {
  521. const auto &creatures = VLC->creh->objects;
  522. bonus->type = Bonus::SPECIAL_UPGRADE;
  523. bonus->subtype = spec.subtype; //base id
  524. bonus->additionalInfo = spec.additionalinfo; //target id
  525. result.push_back(bonus);
  526. //propagate for regular upgrades of base creature
  527. for(auto cre_id : creatures[spec.subtype]->upgrades)
  528. {
  529. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  530. upgradeUpgradedVersion->subtype = cre_id;
  531. result.push_back(upgradeUpgradedVersion);
  532. }
  533. }
  534. break;
  535. case 10: //resource generation
  536. bonus->type = Bonus::GENERATE_RESOURCE;
  537. bonus->subtype = spec.subtype;
  538. result.push_back(bonus);
  539. break;
  540. case 11: //starting skill with mastery (Adrienne)
  541. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  542. break;
  543. case 12: //army speed
  544. bonus->type = Bonus::STACKS_SPEED;
  545. result.push_back(bonus);
  546. break;
  547. case 13: //Dragon bonuses (Mutare)
  548. bonus->type = Bonus::PRIMARY_SKILL;
  549. bonus->valType = Bonus::ADDITIVE_VALUE;
  550. switch(spec.subtype)
  551. {
  552. case 1:
  553. bonus->subtype = PrimarySkill::ATTACK;
  554. break;
  555. case 2:
  556. bonus->subtype = PrimarySkill::DEFENSE;
  557. break;
  558. }
  559. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  560. result.push_back(bonus);
  561. break;
  562. default:
  563. logMod->warn("Unknown hero specialty %d", spec.type);
  564. break;
  565. }
  566. return result;
  567. }
  568. // convert deprecated format
  569. std::vector<std::shared_ptr<Bonus>> SpecialtyBonusToBonuses(const SSpecialtyBonus & spec, int sid)
  570. {
  571. std::vector<std::shared_ptr<Bonus>> result;
  572. for(std::shared_ptr<Bonus> oldBonus : spec.bonuses)
  573. {
  574. oldBonus->sid = sid;
  575. if(oldBonus->type == Bonus::SPECIAL_SPELL_LEV || oldBonus->type == Bonus::SPECIAL_BLESS_DAMAGE)
  576. {
  577. // these bonuses used to auto-scale with hero level
  578. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  579. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  580. result.push_back(newBonus);
  581. }
  582. else if(spec.growsWithLevel)
  583. {
  584. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  585. switch(newBonus->type)
  586. {
  587. case Bonus::SECONDARY_SKILL_PREMY:
  588. break; // ignore - used to be overwritten based on SPECIAL_SECONDARY_SKILL
  589. case Bonus::SPECIAL_SECONDARY_SKILL:
  590. newBonus->type = Bonus::SECONDARY_SKILL_PREMY;
  591. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  592. result.push_back(newBonus);
  593. break;
  594. case Bonus::PRIMARY_SKILL:
  595. if((newBonus->subtype == PrimarySkill::ATTACK || newBonus->subtype == PrimarySkill::DEFENSE) && newBonus->limiter)
  596. {
  597. std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(newBonus->limiter);
  598. if(creatureLimiter)
  599. {
  600. const CCreature * cre = creatureLimiter->creature;
  601. int creStat = newBonus->subtype == PrimarySkill::ATTACK ? cre->getAttack(false) : cre->getDefense(false);
  602. int creLevel = cre->level ? cre->level : 5;
  603. newBonus->updater = std::make_shared<GrowsWithLevelUpdater>(creStat, creLevel);
  604. }
  605. result.push_back(newBonus);
  606. }
  607. break;
  608. default:
  609. result.push_back(newBonus);
  610. }
  611. }
  612. else
  613. {
  614. result.push_back(oldBonus);
  615. }
  616. }
  617. return result;
  618. }
  619. void CHeroHandler::beforeValidate(JsonNode & object)
  620. {
  621. //handle "base" specialty info
  622. JsonNode & specialtyNode = object["specialty"];
  623. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  624. {
  625. const JsonNode & base = specialtyNode["base"];
  626. if(!base.isNull())
  627. {
  628. if(specialtyNode["bonuses"].isNull())
  629. {
  630. logMod->warn("specialty has base without bonuses");
  631. }
  632. else
  633. {
  634. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  635. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  636. JsonUtils::inherit(bonuses[keyValue.first], base);
  637. }
  638. }
  639. }
  640. }
  641. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  642. {
  643. int sid = hero->ID.getNum();
  644. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  645. {
  646. bonus->duration = Bonus::PERMANENT;
  647. bonus->source = Bonus::HERO_SPECIAL;
  648. bonus->sid = sid;
  649. return bonus;
  650. };
  651. //deprecated, used only for original specialties
  652. const JsonNode & specialtiesNode = node["specialties"];
  653. if (!specialtiesNode.isNull())
  654. {
  655. logMod->warn("Hero %s has deprecated specialties format.", hero->getNameTranslated());
  656. for(const JsonNode &specialty : specialtiesNode.Vector())
  657. {
  658. SSpecialtyInfo spec;
  659. spec.type = static_cast<si32>(specialty["type"].Integer());
  660. spec.val = static_cast<si32>(specialty["val"].Integer());
  661. spec.subtype = static_cast<si32>(specialty["subtype"].Integer());
  662. spec.additionalinfo = static_cast<si32>(specialty["info"].Integer());
  663. //we convert after loading completes, to have all identifiers for json logging
  664. hero->specDeprecated.push_back(spec);
  665. }
  666. }
  667. //new(er) format, using bonus system
  668. const JsonNode & specialtyNode = node["specialty"];
  669. if(specialtyNode.getType() == JsonNode::JsonType::DATA_VECTOR)
  670. {
  671. //deprecated middle-aged format
  672. for(const JsonNode & specialty : node["specialty"].Vector())
  673. {
  674. SSpecialtyBonus hs;
  675. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  676. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  677. hs.bonuses.push_back(prepSpec(JsonUtils::parseBonus(bonus)));
  678. hero->specialtyDeprecated.push_back(hs);
  679. }
  680. }
  681. else if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  682. {
  683. //creature specialty - alias for simplicity
  684. if(!specialtyNode["creature"].isNull())
  685. {
  686. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  687. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  688. SSpecialtyInfo spec;
  689. spec.type = 1;
  690. spec.additionalinfo = creature;
  691. hero->specDeprecated.push_back(spec);
  692. });
  693. }
  694. if(!specialtyNode["bonuses"].isNull())
  695. {
  696. //proper new format
  697. for(auto keyValue : specialtyNode["bonuses"].Struct())
  698. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  699. }
  700. }
  701. }
  702. void CHeroHandler::loadExperience()
  703. {
  704. expPerLevel.push_back(0);
  705. expPerLevel.push_back(1000);
  706. expPerLevel.push_back(2000);
  707. expPerLevel.push_back(3200);
  708. expPerLevel.push_back(4600);
  709. expPerLevel.push_back(6200);
  710. expPerLevel.push_back(8000);
  711. expPerLevel.push_back(10000);
  712. expPerLevel.push_back(12200);
  713. expPerLevel.push_back(14700);
  714. expPerLevel.push_back(17500);
  715. expPerLevel.push_back(20600);
  716. expPerLevel.push_back(24320);
  717. expPerLevel.push_back(28784);
  718. expPerLevel.push_back(34140);
  719. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  720. {
  721. auto i = expPerLevel.size() - 1;
  722. auto diff = expPerLevel[i] - expPerLevel[i-1];
  723. diff += diff / 5;
  724. expPerLevel.push_back (expPerLevel[i] + diff);
  725. }
  726. expPerLevel.pop_back();//last value is broken
  727. }
  728. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  729. static std::string genRefName(std::string input)
  730. {
  731. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  732. input[0] = std::tolower(input[0]); // to camelCase
  733. return input;
  734. }
  735. void CHeroHandler::loadBallistics()
  736. {
  737. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  738. ballParser.endLine(); //header
  739. ballParser.endLine();
  740. do
  741. {
  742. ballParser.readString();
  743. ballParser.readString();
  744. CHeroHandler::SBallisticsLevelInfo bli;
  745. bli.keep = static_cast<ui8>(ballParser.readNumber());
  746. bli.tower = static_cast<ui8>(ballParser.readNumber());
  747. bli.gate = static_cast<ui8>(ballParser.readNumber());
  748. bli.wall = static_cast<ui8>(ballParser.readNumber());
  749. bli.shots = static_cast<ui8>(ballParser.readNumber());
  750. bli.noDmg = static_cast<ui8>(ballParser.readNumber());
  751. bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
  752. bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
  753. bli.sum = static_cast<ui8>(ballParser.readNumber());
  754. ballistics.push_back(bli);
  755. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  756. }
  757. while (ballParser.endLine());
  758. }
  759. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  760. {
  761. objects.resize(dataSize);
  762. std::vector<JsonNode> h3Data;
  763. h3Data.reserve(dataSize);
  764. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  765. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  766. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  767. parser.endLine(); //ignore header
  768. parser.endLine();
  769. specParser.endLine(); //ignore header
  770. specParser.endLine();
  771. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  772. {
  773. JsonNode heroData;
  774. heroData["texts"]["name"].String() = parser.readString();
  775. heroData["texts"]["biography"].String() = bioParser.readString();
  776. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  777. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  778. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  779. for(int x=0;x<3;x++)
  780. {
  781. JsonNode armySlot;
  782. armySlot["min"].Float() = parser.readNumber();
  783. armySlot["max"].Float() = parser.readNumber();
  784. armySlot["creature"].String() = genRefName(parser.readString());
  785. heroData["army"].Vector().push_back(armySlot);
  786. }
  787. parser.endLine();
  788. specParser.endLine();
  789. bioParser.endLine();
  790. h3Data.push_back(heroData);
  791. }
  792. return h3Data;
  793. }
  794. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  795. {
  796. size_t index = objects.size();
  797. auto object = loadFromJson(scope, data, name, index);
  798. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  799. objects.push_back(object);
  800. registerObject(scope, "hero", name, object->getIndex());
  801. }
  802. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  803. {
  804. auto object = loadFromJson(scope, data, name, index);
  805. object->imageIndex = static_cast<si32>(index);
  806. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  807. objects[index] = object;
  808. registerObject(scope, "hero", name, object->getIndex());
  809. }
  810. void CHeroHandler::afterLoadFinalization()
  811. {
  812. for(auto & hero : objects)
  813. {
  814. for(auto bonus : hero->specialty)
  815. {
  816. bonus->sid = hero->getIndex();
  817. }
  818. if(hero->specDeprecated.size() > 0 || hero->specialtyDeprecated.size() > 0)
  819. {
  820. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  821. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  822. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  823. {
  824. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  825. convertedBonuses.push_back(b);
  826. }
  827. for(const SSpecialtyBonus & spec : hero->specialtyDeprecated)
  828. {
  829. for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(spec, hero->ID.getNum()))
  830. convertedBonuses.push_back(b);
  831. }
  832. hero->specDeprecated.clear();
  833. hero->specialtyDeprecated.clear();
  834. // store and create json for logging
  835. std::vector<JsonNode> specVec;
  836. std::vector<std::string> specNames;
  837. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  838. {
  839. hero->specialty.push_back(bonus);
  840. specVec.push_back(bonus->toJsonNode());
  841. // find fitting & unique bonus name
  842. std::string bonusName = bonus->nameForBonus();
  843. if(vstd::contains(specNames, bonusName))
  844. {
  845. int suffix = 2;
  846. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  847. suffix++;
  848. bonusName += std::to_string(suffix);
  849. }
  850. specNames.push_back(bonusName);
  851. }
  852. // log new format for easy copy-and-paste
  853. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  854. if(specVec.size() > 1)
  855. {
  856. JsonNode base = JsonUtils::intersect(specVec);
  857. if(base.containsBaseData())
  858. {
  859. specNode["base"] = base;
  860. for(JsonNode & node : specVec)
  861. node = JsonUtils::difference(node, base);
  862. }
  863. }
  864. // add json for bonuses
  865. specNode["bonuses"].Struct();
  866. for(int i = 0; i < specVec.size(); i++)
  867. specNode["bonuses"][specNames[i]] = specVec[i];
  868. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  869. }
  870. }
  871. }
  872. ui32 CHeroHandler::level (ui64 experience) const
  873. {
  874. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  875. }
  876. ui64 CHeroHandler::reqExp (ui32 level) const
  877. {
  878. if(!level)
  879. return 0;
  880. if (level <= expPerLevel.size())
  881. {
  882. return expPerLevel[level-1];
  883. }
  884. else
  885. {
  886. logGlobal->warn("A hero has reached unsupported amount of experience");
  887. return expPerLevel[expPerLevel.size()-1];
  888. }
  889. }
  890. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  891. {
  892. // Look Data/HOTRAITS.txt for reference
  893. std::vector<bool> allowedHeroes;
  894. allowedHeroes.reserve(size());
  895. for(const CHero * hero : objects)
  896. {
  897. allowedHeroes.push_back(!hero->special);
  898. }
  899. return allowedHeroes;
  900. }
  901. VCMI_LIB_NAMESPACE_END