CHeroHandler.cpp 31 KB

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