CHeroHandler.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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::SPECIAL_FIXED_VALUE_ENCHANT;
  510. bonus->subtype = spec.subtype; //spell id
  511. bonus->val = 3; //to match MAXED_BONUS
  512. result.push_back(bonus);
  513. break;
  514. case 8: //peculiar spells - enchantments
  515. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  516. bonus->subtype = spec.subtype; //spell id
  517. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  518. result.push_back(bonus);
  519. break;
  520. case 9: //upgrade creatures
  521. {
  522. const auto &creatures = VLC->creh->objects;
  523. bonus->type = Bonus::SPECIAL_UPGRADE;
  524. bonus->subtype = spec.subtype; //base id
  525. bonus->additionalInfo = spec.additionalinfo; //target id
  526. result.push_back(bonus);
  527. //propagate for regular upgrades of base creature
  528. for(auto cre_id : creatures[spec.subtype]->upgrades)
  529. {
  530. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  531. upgradeUpgradedVersion->subtype = cre_id;
  532. result.push_back(upgradeUpgradedVersion);
  533. }
  534. }
  535. break;
  536. case 10: //resource generation
  537. bonus->type = Bonus::GENERATE_RESOURCE;
  538. bonus->subtype = spec.subtype;
  539. result.push_back(bonus);
  540. break;
  541. case 11: //starting skill with mastery (Adrienne)
  542. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  543. break;
  544. case 12: //army speed
  545. bonus->type = Bonus::STACKS_SPEED;
  546. result.push_back(bonus);
  547. break;
  548. case 13: //Dragon bonuses (Mutare)
  549. bonus->type = Bonus::PRIMARY_SKILL;
  550. bonus->valType = Bonus::ADDITIVE_VALUE;
  551. switch(spec.subtype)
  552. {
  553. case 1:
  554. bonus->subtype = PrimarySkill::ATTACK;
  555. break;
  556. case 2:
  557. bonus->subtype = PrimarySkill::DEFENSE;
  558. break;
  559. }
  560. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  561. result.push_back(bonus);
  562. break;
  563. default:
  564. logMod->warn("Unknown hero specialty %d", spec.type);
  565. break;
  566. }
  567. return result;
  568. }
  569. // convert deprecated format
  570. std::vector<std::shared_ptr<Bonus>> SpecialtyBonusToBonuses(const SSpecialtyBonus & spec, int sid)
  571. {
  572. std::vector<std::shared_ptr<Bonus>> result;
  573. for(std::shared_ptr<Bonus> oldBonus : spec.bonuses)
  574. {
  575. oldBonus->sid = sid;
  576. if(oldBonus->type == Bonus::SPECIAL_SPELL_LEV || oldBonus->type == Bonus::SPECIAL_BLESS_DAMAGE)
  577. {
  578. // these bonuses used to auto-scale with hero level
  579. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  580. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  581. result.push_back(newBonus);
  582. }
  583. else if(spec.growsWithLevel)
  584. {
  585. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  586. switch(newBonus->type)
  587. {
  588. case Bonus::SECONDARY_SKILL_PREMY:
  589. break; // ignore - used to be overwritten based on SPECIAL_SECONDARY_SKILL
  590. case Bonus::SPECIAL_SECONDARY_SKILL:
  591. newBonus->type = Bonus::SECONDARY_SKILL_PREMY;
  592. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  593. result.push_back(newBonus);
  594. break;
  595. case Bonus::PRIMARY_SKILL:
  596. if((newBonus->subtype == PrimarySkill::ATTACK || newBonus->subtype == PrimarySkill::DEFENSE) && newBonus->limiter)
  597. {
  598. std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(newBonus->limiter);
  599. if(creatureLimiter)
  600. {
  601. const CCreature * cre = creatureLimiter->creature;
  602. int creStat = newBonus->subtype == PrimarySkill::ATTACK ? cre->getAttack(false) : cre->getDefense(false);
  603. int creLevel = cre->level ? cre->level : 5;
  604. newBonus->updater = std::make_shared<GrowsWithLevelUpdater>(creStat, creLevel);
  605. }
  606. result.push_back(newBonus);
  607. }
  608. break;
  609. default:
  610. result.push_back(newBonus);
  611. }
  612. }
  613. else
  614. {
  615. result.push_back(oldBonus);
  616. }
  617. }
  618. return result;
  619. }
  620. void CHeroHandler::beforeValidate(JsonNode & object)
  621. {
  622. //handle "base" specialty info
  623. JsonNode & specialtyNode = object["specialty"];
  624. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  625. {
  626. const JsonNode & base = specialtyNode["base"];
  627. if(!base.isNull())
  628. {
  629. if(specialtyNode["bonuses"].isNull())
  630. {
  631. logMod->warn("specialty has base without bonuses");
  632. }
  633. else
  634. {
  635. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  636. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  637. JsonUtils::inherit(bonuses[keyValue.first], base);
  638. }
  639. }
  640. }
  641. }
  642. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  643. {
  644. int sid = hero->ID.getNum();
  645. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  646. {
  647. bonus->duration = Bonus::PERMANENT;
  648. bonus->source = Bonus::HERO_SPECIAL;
  649. bonus->sid = sid;
  650. return bonus;
  651. };
  652. //deprecated, used only for original specialties
  653. const JsonNode & specialtiesNode = node["specialties"];
  654. if (!specialtiesNode.isNull())
  655. {
  656. logMod->warn("Hero %s has deprecated specialties format.", hero->getNameTranslated());
  657. for(const JsonNode &specialty : specialtiesNode.Vector())
  658. {
  659. SSpecialtyInfo spec;
  660. spec.type = static_cast<si32>(specialty["type"].Integer());
  661. spec.val = static_cast<si32>(specialty["val"].Integer());
  662. spec.subtype = static_cast<si32>(specialty["subtype"].Integer());
  663. spec.additionalinfo = static_cast<si32>(specialty["info"].Integer());
  664. //we convert after loading completes, to have all identifiers for json logging
  665. hero->specDeprecated.push_back(spec);
  666. }
  667. }
  668. //new(er) format, using bonus system
  669. const JsonNode & specialtyNode = node["specialty"];
  670. if(specialtyNode.getType() == JsonNode::JsonType::DATA_VECTOR)
  671. {
  672. //deprecated middle-aged format
  673. for(const JsonNode & specialty : node["specialty"].Vector())
  674. {
  675. SSpecialtyBonus hs;
  676. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  677. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  678. hs.bonuses.push_back(prepSpec(JsonUtils::parseBonus(bonus)));
  679. hero->specialtyDeprecated.push_back(hs);
  680. }
  681. }
  682. else if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  683. {
  684. //creature specialty - alias for simplicity
  685. if(!specialtyNode["creature"].isNull())
  686. {
  687. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  688. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  689. SSpecialtyInfo spec;
  690. spec.type = 1;
  691. spec.additionalinfo = creature;
  692. hero->specDeprecated.push_back(spec);
  693. });
  694. }
  695. if(!specialtyNode["bonuses"].isNull())
  696. {
  697. //proper new format
  698. for(auto keyValue : specialtyNode["bonuses"].Struct())
  699. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  700. }
  701. }
  702. }
  703. void CHeroHandler::loadExperience()
  704. {
  705. expPerLevel.push_back(0);
  706. expPerLevel.push_back(1000);
  707. expPerLevel.push_back(2000);
  708. expPerLevel.push_back(3200);
  709. expPerLevel.push_back(4600);
  710. expPerLevel.push_back(6200);
  711. expPerLevel.push_back(8000);
  712. expPerLevel.push_back(10000);
  713. expPerLevel.push_back(12200);
  714. expPerLevel.push_back(14700);
  715. expPerLevel.push_back(17500);
  716. expPerLevel.push_back(20600);
  717. expPerLevel.push_back(24320);
  718. expPerLevel.push_back(28784);
  719. expPerLevel.push_back(34140);
  720. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  721. {
  722. auto i = expPerLevel.size() - 1;
  723. auto diff = expPerLevel[i] - expPerLevel[i-1];
  724. diff += diff / 5;
  725. expPerLevel.push_back (expPerLevel[i] + diff);
  726. }
  727. expPerLevel.pop_back();//last value is broken
  728. }
  729. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  730. static std::string genRefName(std::string input)
  731. {
  732. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  733. input[0] = std::tolower(input[0]); // to camelCase
  734. return input;
  735. }
  736. void CHeroHandler::loadBallistics()
  737. {
  738. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  739. ballParser.endLine(); //header
  740. ballParser.endLine();
  741. do
  742. {
  743. ballParser.readString();
  744. ballParser.readString();
  745. CHeroHandler::SBallisticsLevelInfo bli;
  746. bli.keep = static_cast<ui8>(ballParser.readNumber());
  747. bli.tower = static_cast<ui8>(ballParser.readNumber());
  748. bli.gate = static_cast<ui8>(ballParser.readNumber());
  749. bli.wall = static_cast<ui8>(ballParser.readNumber());
  750. bli.shots = static_cast<ui8>(ballParser.readNumber());
  751. bli.noDmg = static_cast<ui8>(ballParser.readNumber());
  752. bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
  753. bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
  754. bli.sum = static_cast<ui8>(ballParser.readNumber());
  755. ballistics.push_back(bli);
  756. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  757. }
  758. while (ballParser.endLine());
  759. }
  760. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  761. {
  762. objects.resize(dataSize);
  763. std::vector<JsonNode> h3Data;
  764. h3Data.reserve(dataSize);
  765. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  766. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  767. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  768. parser.endLine(); //ignore header
  769. parser.endLine();
  770. specParser.endLine(); //ignore header
  771. specParser.endLine();
  772. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  773. {
  774. JsonNode heroData;
  775. heroData["texts"]["name"].String() = parser.readString();
  776. heroData["texts"]["biography"].String() = bioParser.readString();
  777. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  778. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  779. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  780. for(int x=0;x<3;x++)
  781. {
  782. JsonNode armySlot;
  783. armySlot["min"].Float() = parser.readNumber();
  784. armySlot["max"].Float() = parser.readNumber();
  785. armySlot["creature"].String() = genRefName(parser.readString());
  786. heroData["army"].Vector().push_back(armySlot);
  787. }
  788. parser.endLine();
  789. specParser.endLine();
  790. bioParser.endLine();
  791. h3Data.push_back(heroData);
  792. }
  793. return h3Data;
  794. }
  795. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  796. {
  797. size_t index = objects.size();
  798. auto object = loadFromJson(scope, data, name, index);
  799. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  800. objects.push_back(object);
  801. registerObject(scope, "hero", name, object->getIndex());
  802. }
  803. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  804. {
  805. auto object = loadFromJson(scope, data, name, index);
  806. object->imageIndex = static_cast<si32>(index);
  807. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  808. objects[index] = object;
  809. registerObject(scope, "hero", name, object->getIndex());
  810. }
  811. void CHeroHandler::afterLoadFinalization()
  812. {
  813. for(auto & hero : objects)
  814. {
  815. for(auto bonus : hero->specialty)
  816. {
  817. bonus->sid = hero->getIndex();
  818. }
  819. if(hero->specDeprecated.size() > 0 || hero->specialtyDeprecated.size() > 0)
  820. {
  821. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  822. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  823. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  824. {
  825. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  826. convertedBonuses.push_back(b);
  827. }
  828. for(const SSpecialtyBonus & spec : hero->specialtyDeprecated)
  829. {
  830. for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(spec, hero->ID.getNum()))
  831. convertedBonuses.push_back(b);
  832. }
  833. hero->specDeprecated.clear();
  834. hero->specialtyDeprecated.clear();
  835. // store and create json for logging
  836. std::vector<JsonNode> specVec;
  837. std::vector<std::string> specNames;
  838. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  839. {
  840. hero->specialty.push_back(bonus);
  841. specVec.push_back(bonus->toJsonNode());
  842. // find fitting & unique bonus name
  843. std::string bonusName = bonus->nameForBonus();
  844. if(vstd::contains(specNames, bonusName))
  845. {
  846. int suffix = 2;
  847. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  848. suffix++;
  849. bonusName += std::to_string(suffix);
  850. }
  851. specNames.push_back(bonusName);
  852. }
  853. // log new format for easy copy-and-paste
  854. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  855. if(specVec.size() > 1)
  856. {
  857. JsonNode base = JsonUtils::intersect(specVec);
  858. if(base.containsBaseData())
  859. {
  860. specNode["base"] = base;
  861. for(JsonNode & node : specVec)
  862. node = JsonUtils::difference(node, base);
  863. }
  864. }
  865. // add json for bonuses
  866. specNode["bonuses"].Struct();
  867. for(int i = 0; i < specVec.size(); i++)
  868. specNode["bonuses"][specNames[i]] = specVec[i];
  869. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  870. }
  871. }
  872. }
  873. ui32 CHeroHandler::level (ui64 experience) const
  874. {
  875. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  876. }
  877. ui64 CHeroHandler::reqExp (ui32 level) const
  878. {
  879. if(!level)
  880. return 0;
  881. if (level <= expPerLevel.size())
  882. {
  883. return expPerLevel[level-1];
  884. }
  885. else
  886. {
  887. logGlobal->warn("A hero has reached unsupported amount of experience");
  888. return expPerLevel[expPerLevel.size()-1];
  889. }
  890. }
  891. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  892. {
  893. // Look Data/HOTRAITS.txt for reference
  894. std::vector<bool> allowedHeroes;
  895. allowedHeroes.reserve(size());
  896. for(const CHero * hero : objects)
  897. {
  898. allowedHeroes.push_back(!hero->special);
  899. }
  900. return allowedHeroes;
  901. }
  902. VCMI_LIB_NAMESPACE_END