CHeroHandler.cpp 33 KB

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