CHeroHandler.cpp 31 KB

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