2
0

CHeroHandler.cpp 32 KB

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