2
0

CHeroHandler.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. * CHeroHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CHeroHandler.h"
  12. #include "CGeneralTextHandler.h"
  13. #include "filesystem/Filesystem.h"
  14. #include "VCMI_Lib.h"
  15. #include "JsonNode.h"
  16. #include "StringConstants.h"
  17. #include "battle/BattleHex.h"
  18. #include "CCreatureHandler.h"
  19. #include "CModHandler.h"
  20. #include "CTownHandler.h"
  21. #include "mapObjects/CObjectHandler.h" //for hero specialty
  22. #include "CSkillHandler.h"
  23. #include <math.h>
  24. #include "mapObjects/CObjectClassesHandler.h"
  25. #include "BattleFieldHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. CHero::CHero() = default;
  28. CHero::~CHero() = default;
  29. int32_t CHero::getIndex() const
  30. {
  31. return ID.getNum();
  32. }
  33. int32_t CHero::getIconIndex() const
  34. {
  35. return imageIndex;
  36. }
  37. std::string CHero::getJsonKey() const
  38. {
  39. return modScope + ':' + identifier;;
  40. }
  41. HeroTypeID CHero::getId() const
  42. {
  43. return ID;
  44. }
  45. std::string CHero::getNameTranslated() const
  46. {
  47. return VLC->generaltexth->translate(getNameTextID());
  48. }
  49. std::string CHero::getBiographyTranslated() const
  50. {
  51. return VLC->generaltexth->translate(getBiographyTextID());
  52. }
  53. std::string CHero::getSpecialtyNameTranslated() const
  54. {
  55. return VLC->generaltexth->translate(getSpecialtyNameTextID());
  56. }
  57. std::string CHero::getSpecialtyDescriptionTranslated() const
  58. {
  59. return VLC->generaltexth->translate(getSpecialtyDescriptionTextID());
  60. }
  61. std::string CHero::getSpecialtyTooltipTranslated() const
  62. {
  63. return VLC->generaltexth->translate(getSpecialtyTooltipTextID());
  64. }
  65. std::string CHero::getNameTextID() const
  66. {
  67. return TextIdentifier("hero", modScope, identifier, "name").get();
  68. }
  69. std::string CHero::getBiographyTextID() const
  70. {
  71. return TextIdentifier("hero", modScope, identifier, "biography").get();
  72. }
  73. std::string CHero::getSpecialtyNameTextID() const
  74. {
  75. return TextIdentifier("hero", modScope, identifier, "specialty", "name").get();
  76. }
  77. std::string CHero::getSpecialtyDescriptionTextID() const
  78. {
  79. return TextIdentifier("hero", modScope, identifier, "specialty", "description").get();
  80. }
  81. std::string CHero::getSpecialtyTooltipTextID() const
  82. {
  83. return TextIdentifier("hero", modScope, identifier, "specialty", "tooltip").get();
  84. }
  85. void CHero::registerIcons(const IconRegistar & cb) const
  86. {
  87. cb(getIconIndex(), 0, "UN32", iconSpecSmall);
  88. cb(getIconIndex(), 0, "UN44", iconSpecLarge);
  89. cb(getIconIndex(), 0, "PORTRAITSLARGE", portraitLarge);
  90. cb(getIconIndex(), 0, "PORTRAITSSMALL", portraitSmall);
  91. }
  92. void CHero::updateFrom(const JsonNode & data)
  93. {
  94. //todo: CHero::updateFrom
  95. }
  96. void CHero::serializeJson(JsonSerializeFormat & handler)
  97. {
  98. }
  99. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  100. {
  101. int totalProb = 0;
  102. for(auto & possible : possibles)
  103. {
  104. totalProb += secSkillProbability[possible];
  105. }
  106. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  107. {
  108. auto ran = rand.nextInt(totalProb - 1);
  109. for(auto & possible : possibles)
  110. {
  111. ran -= secSkillProbability[possible];
  112. if(ran < 0)
  113. {
  114. return possible;
  115. }
  116. }
  117. }
  118. // FIXME: select randomly? How H3 handles such rare situation?
  119. return *possibles.begin();
  120. }
  121. bool CHeroClass::isMagicHero() const
  122. {
  123. return affinity == MAGIC;
  124. }
  125. EAlignment::EAlignment CHeroClass::getAlignment() const
  126. {
  127. return EAlignment::EAlignment((*VLC->townh)[faction]->alignment);
  128. }
  129. int32_t CHeroClass::getIndex() const
  130. {
  131. return id.getNum();
  132. }
  133. int32_t CHeroClass::getIconIndex() const
  134. {
  135. return getIndex();
  136. }
  137. std::string CHeroClass::getJsonKey() const
  138. {
  139. return modScope + ':' + identifier;;
  140. }
  141. HeroClassID CHeroClass::getId() const
  142. {
  143. return id;
  144. }
  145. void CHeroClass::registerIcons(const IconRegistar & cb) const
  146. {
  147. }
  148. std::string CHeroClass::getNameTranslated() const
  149. {
  150. return VLC->generaltexth->translate(getNameTextID());
  151. }
  152. std::string CHeroClass::getNameTextID() const
  153. {
  154. return TextIdentifier("heroClass", modScope, identifier, "name").get();
  155. }
  156. void CHeroClass::updateFrom(const JsonNode & data)
  157. {
  158. //TODO: CHeroClass::updateFrom
  159. }
  160. void CHeroClass::serializeJson(JsonSerializeFormat & handler)
  161. {
  162. }
  163. CHeroClass::CHeroClass()
  164. : faction(0), id(), affinity(0), defaultTavernChance(0), commander(nullptr)
  165. {
  166. }
  167. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill::PrimarySkill pSkill)
  168. {
  169. const auto & skillName = PrimarySkill::names[pSkill];
  170. auto currentPrimarySkillValue = (int)node["primarySkills"][skillName].Integer();
  171. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  172. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  173. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  174. {
  175. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  176. heroClass->getNameTranslated(), currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  177. currentPrimarySkillValue = primarySkillLegalMinimum;
  178. }
  179. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  180. heroClass->primarySkillLowLevel.push_back((int)node["lowLevelChance"][skillName].Float());
  181. heroClass->primarySkillHighLevel.push_back((int)node["highLevelChance"][skillName].Float());
  182. }
  183. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  184. {
  185. static const std::vector<std::string> typeNames = { "heroClass" };
  186. return typeNames;
  187. }
  188. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  189. {
  190. assert(identifier.find(':') == std::string::npos);
  191. assert(!scope.empty());
  192. std::string affinityStr[2] = { "might", "magic" };
  193. auto heroClass = new CHeroClass();
  194. heroClass->id = HeroClassID(index);
  195. heroClass->identifier = identifier;
  196. heroClass->modScope = scope;
  197. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  198. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  199. //MODS COMPATIBILITY FOR 0.96
  200. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  201. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  202. VLC->generaltexth->registerString(scope, heroClass->getNameTextID(), node["name"].String());
  203. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  204. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  205. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  206. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  207. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  208. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  209. if(percentSumm != 100)
  210. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  211. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  212. if(percentSumm != 100)
  213. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  214. for(auto skillPair : node["secondarySkills"].Struct())
  215. {
  216. int probability = static_cast<int>(skillPair.second.Integer());
  217. VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  218. {
  219. if(heroClass->secSkillProbability.size() <= skillID)
  220. heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
  221. heroClass->secSkillProbability[skillID] = probability;
  222. });
  223. }
  224. VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
  225. [=](si32 commanderID)
  226. {
  227. heroClass->commander = VLC->creh->objects[commanderID];
  228. });
  229. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  230. for(auto & tavern : node["tavern"].Struct())
  231. {
  232. int value = static_cast<int>(tavern.second.Float());
  233. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  234. [=](si32 factionID)
  235. {
  236. heroClass->selectionProbability[factionID] = value;
  237. });
  238. }
  239. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  240. [=](si32 factionID)
  241. {
  242. heroClass->faction = factionID;
  243. });
  244. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  245. {
  246. JsonNode classConf = node["mapObject"];
  247. classConf["heroClass"].String() = identifier;
  248. classConf.setMeta(scope);
  249. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  250. });
  251. return heroClass;
  252. }
  253. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  254. {
  255. objects.resize(dataSize);
  256. std::vector<JsonNode> h3Data;
  257. h3Data.reserve(dataSize);
  258. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  259. parser.endLine(); // header
  260. parser.endLine();
  261. for (size_t i=0; i<dataSize; i++)
  262. {
  263. JsonNode entry;
  264. entry["name"].String() = parser.readString();
  265. parser.readNumber(); // unused aggression
  266. for (auto & name : PrimarySkill::names)
  267. entry["primarySkills"][name].Float() = parser.readNumber();
  268. for (auto & name : PrimarySkill::names)
  269. entry["lowLevelChance"][name].Float() = parser.readNumber();
  270. for (auto & name : PrimarySkill::names)
  271. entry["highLevelChance"][name].Float() = parser.readNumber();
  272. for (auto & name : NSecondarySkill::names)
  273. entry["secondarySkills"][name].Float() = parser.readNumber();
  274. for(auto & name : ETownType::names)
  275. entry["tavern"][name].Float() = parser.readNumber();
  276. parser.endLine();
  277. h3Data.push_back(entry);
  278. }
  279. return h3Data;
  280. }
  281. void CHeroClassHandler::afterLoadFinalization()
  282. {
  283. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  284. for(CHeroClass * heroClass : objects)
  285. {
  286. for(CFaction * faction : VLC->townh->objects)
  287. {
  288. if (!faction->town)
  289. continue;
  290. if (heroClass->selectionProbability.count(faction->getIndex()))
  291. continue;
  292. float chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  293. heroClass->selectionProbability[faction->getIndex()] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  294. }
  295. // set default probabilities for gaining secondary skills where not loaded previously
  296. heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
  297. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  298. {
  299. if(heroClass->secSkillProbability[skillID] < 0)
  300. {
  301. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  302. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->getJsonKey());
  303. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  304. }
  305. }
  306. }
  307. for(CHeroClass * hc : objects)
  308. {
  309. if (!hc->imageMapMale.empty())
  310. {
  311. JsonNode templ;
  312. templ["animation"].String() = hc->imageMapMale;
  313. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  314. }
  315. }
  316. }
  317. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  318. {
  319. return std::vector<bool>(size(), true);
  320. }
  321. CHeroClassHandler::~CHeroClassHandler() = default;
  322. CHeroHandler::~CHeroHandler() = default;
  323. CHeroHandler::CHeroHandler()
  324. {
  325. 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(scope, hero->getNameTextID(), node["texts"]["name"].String());
  344. VLC->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"].String());
  345. VLC->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  346. VLC->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  347. VLC->generaltexth->registerString(scope, 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. {
  503. auto limiter = std::make_shared<HasAnotherBonusLimiter>(Bonus::GENERAL_DAMAGE_PREMY,Bonus::SPELL_EFFECT);
  504. limiter->sid = spec.subtype; //spell id if you ever wanted to use it otherwise
  505. limiter->isSourceIDRelevant = true;
  506. bonus->type = Bonus::GENERAL_DAMAGE_PREMY;
  507. bonus->updater.reset(new TimesHeroLevelUpdater());
  508. bonus->addLimiter(limiter);
  509. result.push_back(bonus);
  510. break;
  511. }
  512. case 7: //maxed mastery for spell
  513. bonus->type = Bonus::SPELL;
  514. bonus->subtype = spec.subtype; //spell id
  515. bonus->val = 3; //to match MAXED_SPELL
  516. bonus->valType = Bonus::INDEPENDENT_MAX;
  517. result.push_back(bonus);
  518. break;
  519. case 8: //peculiar spells - enchantments
  520. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  521. bonus->subtype = spec.subtype; //spell id
  522. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  523. result.push_back(bonus);
  524. break;
  525. case 9: //upgrade creatures
  526. {
  527. const auto &creatures = VLC->creh->objects;
  528. bonus->type = Bonus::SPECIAL_UPGRADE;
  529. bonus->subtype = spec.subtype; //base id
  530. bonus->additionalInfo = spec.additionalinfo; //target id
  531. result.push_back(bonus);
  532. //propagate for regular upgrades of base creature
  533. for(auto cre_id : creatures[spec.subtype]->upgrades)
  534. {
  535. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  536. upgradeUpgradedVersion->subtype = cre_id;
  537. result.push_back(upgradeUpgradedVersion);
  538. }
  539. }
  540. break;
  541. case 10: //resource generation
  542. bonus->type = Bonus::GENERATE_RESOURCE;
  543. bonus->subtype = spec.subtype;
  544. result.push_back(bonus);
  545. break;
  546. case 11: //starting skill with mastery (Adrienne)
  547. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  548. break;
  549. case 12: //army speed
  550. bonus->type = Bonus::STACKS_SPEED;
  551. result.push_back(bonus);
  552. break;
  553. case 13: //Dragon bonuses (Mutare)
  554. bonus->type = Bonus::PRIMARY_SKILL;
  555. bonus->valType = Bonus::ADDITIVE_VALUE;
  556. switch(spec.subtype)
  557. {
  558. case 1:
  559. bonus->subtype = PrimarySkill::ATTACK;
  560. break;
  561. case 2:
  562. bonus->subtype = PrimarySkill::DEFENSE;
  563. break;
  564. }
  565. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  566. result.push_back(bonus);
  567. break;
  568. default:
  569. logMod->warn("Unknown hero specialty %d", spec.type);
  570. break;
  571. }
  572. return result;
  573. }
  574. void CHeroHandler::beforeValidate(JsonNode & object)
  575. {
  576. //handle "base" specialty info
  577. JsonNode & specialtyNode = object["specialty"];
  578. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  579. {
  580. const JsonNode & base = specialtyNode["base"];
  581. if(!base.isNull())
  582. {
  583. if(specialtyNode["bonuses"].isNull())
  584. {
  585. logMod->warn("specialty has base without bonuses");
  586. }
  587. else
  588. {
  589. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  590. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  591. JsonUtils::inherit(bonuses[keyValue.first], base);
  592. }
  593. }
  594. }
  595. }
  596. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  597. {
  598. int sid = hero->ID.getNum();
  599. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  600. {
  601. bonus->duration = Bonus::PERMANENT;
  602. bonus->source = Bonus::HERO_SPECIAL;
  603. bonus->sid = sid;
  604. return bonus;
  605. };
  606. //new format, using bonus system
  607. const JsonNode & specialtyNode = node["specialty"];
  608. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  609. {
  610. //creature specialty - alias for simplicity
  611. if(!specialtyNode["creature"].isNull())
  612. {
  613. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  614. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  615. SSpecialtyInfo spec;
  616. spec.type = 1;
  617. spec.additionalinfo = creature;
  618. hero->specDeprecated.push_back(spec);
  619. });
  620. }
  621. if(!specialtyNode["bonuses"].isNull())
  622. {
  623. //proper new format
  624. for(auto keyValue : specialtyNode["bonuses"].Struct())
  625. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  626. }
  627. }
  628. else
  629. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  630. }
  631. void CHeroHandler::loadExperience()
  632. {
  633. expPerLevel.push_back(0);
  634. expPerLevel.push_back(1000);
  635. expPerLevel.push_back(2000);
  636. expPerLevel.push_back(3200);
  637. expPerLevel.push_back(4600);
  638. expPerLevel.push_back(6200);
  639. expPerLevel.push_back(8000);
  640. expPerLevel.push_back(10000);
  641. expPerLevel.push_back(12200);
  642. expPerLevel.push_back(14700);
  643. expPerLevel.push_back(17500);
  644. expPerLevel.push_back(20600);
  645. expPerLevel.push_back(24320);
  646. expPerLevel.push_back(28784);
  647. expPerLevel.push_back(34140);
  648. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  649. {
  650. auto i = expPerLevel.size() - 1;
  651. auto diff = expPerLevel[i] - expPerLevel[i-1];
  652. diff += diff / 5;
  653. expPerLevel.push_back (expPerLevel[i] + diff);
  654. }
  655. expPerLevel.pop_back();//last value is broken
  656. }
  657. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  658. static std::string genRefName(std::string input)
  659. {
  660. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  661. input[0] = std::tolower(input[0]); // to camelCase
  662. return input;
  663. }
  664. void CHeroHandler::loadBallistics()
  665. {
  666. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  667. ballParser.endLine(); //header
  668. ballParser.endLine();
  669. do
  670. {
  671. ballParser.readString();
  672. ballParser.readString();
  673. CHeroHandler::SBallisticsLevelInfo bli;
  674. bli.keep = static_cast<ui8>(ballParser.readNumber());
  675. bli.tower = static_cast<ui8>(ballParser.readNumber());
  676. bli.gate = static_cast<ui8>(ballParser.readNumber());
  677. bli.wall = static_cast<ui8>(ballParser.readNumber());
  678. bli.shots = static_cast<ui8>(ballParser.readNumber());
  679. bli.noDmg = static_cast<ui8>(ballParser.readNumber());
  680. bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
  681. bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
  682. bli.sum = static_cast<ui8>(ballParser.readNumber());
  683. ballistics.push_back(bli);
  684. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  685. }
  686. while (ballParser.endLine());
  687. }
  688. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  689. {
  690. objects.resize(dataSize);
  691. std::vector<JsonNode> h3Data;
  692. h3Data.reserve(dataSize);
  693. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  694. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  695. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  696. parser.endLine(); //ignore header
  697. parser.endLine();
  698. specParser.endLine(); //ignore header
  699. specParser.endLine();
  700. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  701. {
  702. JsonNode heroData;
  703. heroData["texts"]["name"].String() = parser.readString();
  704. heroData["texts"]["biography"].String() = bioParser.readString();
  705. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  706. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  707. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  708. for(int x=0;x<3;x++)
  709. {
  710. JsonNode armySlot;
  711. armySlot["min"].Float() = parser.readNumber();
  712. armySlot["max"].Float() = parser.readNumber();
  713. armySlot["creature"].String() = genRefName(parser.readString());
  714. heroData["army"].Vector().push_back(armySlot);
  715. }
  716. parser.endLine();
  717. specParser.endLine();
  718. bioParser.endLine();
  719. h3Data.push_back(heroData);
  720. }
  721. return h3Data;
  722. }
  723. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  724. {
  725. size_t index = objects.size();
  726. auto object = loadFromJson(scope, data, name, index);
  727. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  728. objects.push_back(object);
  729. registerObject(scope, "hero", name, object->getIndex());
  730. }
  731. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  732. {
  733. auto object = loadFromJson(scope, data, name, index);
  734. object->imageIndex = static_cast<si32>(index);
  735. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  736. objects[index] = object;
  737. registerObject(scope, "hero", name, object->getIndex());
  738. }
  739. void CHeroHandler::afterLoadFinalization()
  740. {
  741. for(auto & hero : objects)
  742. {
  743. for(auto bonus : hero->specialty)
  744. {
  745. bonus->sid = hero->getIndex();
  746. }
  747. if(hero->specDeprecated.size() > 0)
  748. {
  749. logMod->debug("Converting specialty format for hero %s(%s)", hero->getNameTranslated(), FactionID::encode(hero->heroClass->faction));
  750. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  751. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  752. {
  753. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  754. convertedBonuses.push_back(b);
  755. }
  756. hero->specDeprecated.clear();
  757. // store and create json for logging
  758. std::vector<JsonNode> specVec;
  759. std::vector<std::string> specNames;
  760. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  761. {
  762. hero->specialty.push_back(bonus);
  763. specVec.push_back(bonus->toJsonNode());
  764. // find fitting & unique bonus name
  765. std::string bonusName = bonus->nameForBonus();
  766. if(vstd::contains(specNames, bonusName))
  767. {
  768. int suffix = 2;
  769. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  770. suffix++;
  771. bonusName += std::to_string(suffix);
  772. }
  773. specNames.push_back(bonusName);
  774. }
  775. // log new format for easy copy-and-paste
  776. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  777. if(specVec.size() > 1)
  778. {
  779. JsonNode base = JsonUtils::intersect(specVec);
  780. if(base.containsBaseData())
  781. {
  782. specNode["base"] = base;
  783. for(JsonNode & node : specVec)
  784. node = JsonUtils::difference(node, base);
  785. }
  786. }
  787. // add json for bonuses
  788. specNode["bonuses"].Struct();
  789. for(int i = 0; i < specVec.size(); i++)
  790. specNode["bonuses"][specNames[i]] = specVec[i];
  791. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  792. }
  793. }
  794. }
  795. ui32 CHeroHandler::level (ui64 experience) const
  796. {
  797. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  798. }
  799. ui64 CHeroHandler::reqExp (ui32 level) const
  800. {
  801. if(!level)
  802. return 0;
  803. if (level <= expPerLevel.size())
  804. {
  805. return expPerLevel[level-1];
  806. }
  807. else
  808. {
  809. logGlobal->warn("A hero has reached unsupported amount of experience");
  810. return expPerLevel[expPerLevel.size()-1];
  811. }
  812. }
  813. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  814. {
  815. // Look Data/HOTRAITS.txt for reference
  816. std::vector<bool> allowedHeroes;
  817. allowedHeroes.reserve(size());
  818. for(const CHero * hero : objects)
  819. {
  820. allowedHeroes.push_back(!hero->special);
  821. }
  822. return allowedHeroes;
  823. }
  824. VCMI_LIB_NAMESPACE_END