CHeroHandler.cpp 31 KB

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