CHeroHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 "CHero.h"
  13. #include "../../GameLibrary.h"
  14. #include "../../constants/StringConstants.h"
  15. #include "../../CCreatureHandler.h"
  16. #include "../../IGameSettings.h"
  17. #include "../../bonuses/Limiters.h"
  18. #include "../../bonuses/Updaters.h"
  19. #include "../../json/JsonBonus.h"
  20. #include "../../json/JsonUtils.h"
  21. #include "../../modding/IdentifierStorage.h"
  22. #include "../../CSkillHandler.h"
  23. #include "../../texts/CGeneralTextHandler.h"
  24. #include "../../texts/CLegacyConfigParser.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. CHeroHandler::~CHeroHandler() = default;
  27. CHeroHandler::CHeroHandler()
  28. {
  29. loadExperience();
  30. }
  31. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  32. {
  33. static const std::vector<std::string> typeNames = { "hero" };
  34. return typeNames;
  35. }
  36. std::shared_ptr<CHero> CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  37. {
  38. assert(identifier.find(':') == std::string::npos);
  39. assert(!scope.empty());
  40. auto hero = std::make_shared<CHero>();
  41. hero->ID = HeroTypeID(index);
  42. hero->identifier = identifier;
  43. hero->modScope = scope;
  44. hero->gender = node["female"].Bool() ? EHeroGender::FEMALE : EHeroGender::MALE;
  45. hero->special = node["special"].Bool();
  46. //Default - both false
  47. hero->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  48. hero->onlyOnMapWithoutWater = node["onlyOnMapWithoutWater"].Bool();
  49. LIBRARY->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"]);
  50. LIBRARY->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"]);
  51. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"]);
  52. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"]);
  53. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"]);
  54. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  55. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  56. hero->portraitSmall = node["images"]["small"].String();
  57. hero->portraitLarge = node["images"]["large"].String();
  58. hero->battleImage = AnimationPath::fromJson(node["battleImage"]);
  59. loadHeroArmy(hero.get(), node);
  60. loadHeroSkills(hero.get(), node);
  61. loadHeroSpecialty(hero.get(), node);
  62. LIBRARY->identifiers()->requestIdentifier("heroClass", node["class"],
  63. [=](si32 classID)
  64. {
  65. hero->heroClass = HeroClassID(classID).toHeroClass();
  66. });
  67. return hero;
  68. }
  69. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node) const
  70. {
  71. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  72. hero->initialArmy.resize(node["army"].Vector().size());
  73. for (size_t i=0; i< hero->initialArmy.size(); i++)
  74. {
  75. const JsonNode & source = node["army"].Vector()[i];
  76. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  77. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  78. if (hero->initialArmy[i].minAmount > hero->initialArmy[i].maxAmount)
  79. {
  80. logMod->error("Hero %s has minimal army size (%d) greater than maximal size (%d)!", hero->getJsonKey(), hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  81. std::swap(hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  82. }
  83. LIBRARY->identifiers()->requestIdentifier("creature", source["creature"], [=](si32 creature)
  84. {
  85. hero->initialArmy[i].creature = CreatureID(creature);
  86. });
  87. }
  88. }
  89. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node) const
  90. {
  91. for(const JsonNode &set : node["skills"].Vector())
  92. {
  93. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  94. if (skillLevel < MasteryLevel::LEVELS_SIZE)
  95. {
  96. size_t currentIndex = hero->secSkillsInit.size();
  97. hero->secSkillsInit.emplace_back(SecondarySkill(-1), skillLevel);
  98. LIBRARY->identifiers()->requestIdentifier("skill", set["skill"], [=](si32 id)
  99. {
  100. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  101. });
  102. }
  103. else
  104. {
  105. logMod->error("Unknown skill level: %s", set["level"].String());
  106. }
  107. }
  108. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  109. hero->haveSpellBook = !node["spellbook"].isNull();
  110. for(const JsonNode & spell : node["spellbook"].Vector())
  111. {
  112. LIBRARY->identifiers()->requestIdentifier("spell", spell,
  113. [=](si32 spellID)
  114. {
  115. hero->spells.insert(SpellID(spellID));
  116. });
  117. }
  118. }
  119. /// creates standard H3 hero specialty for creatures
  120. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createCreatureSpecialty(CreatureID cid) const
  121. {
  122. std::vector<std::shared_ptr<Bonus>> result;
  123. const auto & specCreature = *cid.toCreature();
  124. int stepSize = specCreature.getLevel() ? specCreature.getLevel() : 5;
  125. {
  126. auto bonus = std::make_shared<Bonus>();
  127. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  128. bonus->type = BonusType::STACKS_SPEED;
  129. bonus->val = 1;
  130. result.push_back(bonus);
  131. }
  132. {
  133. auto bonus = std::make_shared<Bonus>();
  134. bonus->type = BonusType::PRIMARY_SKILL;
  135. bonus->subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  136. bonus->val = 0;
  137. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  138. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  139. result.push_back(bonus);
  140. }
  141. {
  142. auto bonus = std::make_shared<Bonus>();
  143. bonus->type = BonusType::PRIMARY_SKILL;
  144. bonus->subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  145. bonus->val = 0;
  146. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  147. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  148. result.push_back(bonus);
  149. }
  150. return result;
  151. }
  152. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createSecondarySkillSpecialty(SecondarySkill skillID) const
  153. {
  154. std::vector<std::shared_ptr<Bonus>> result;
  155. const auto & skillPtr = LIBRARY->skillh->objects[skillID.getNum()];
  156. if (skillPtr->specialtyTargetBonuses.empty())
  157. logMod->warn("Skill '%s' does not supports generic specialties!", skillPtr->getJsonKey());
  158. for (const auto & bonus : skillPtr->specialtyTargetBonuses)
  159. result.push_back(std::make_shared<Bonus>(*bonus));
  160. return result;
  161. }
  162. void CHeroHandler::beforeValidate(JsonNode & object)
  163. {
  164. //handle "base" specialty info
  165. JsonNode & specialtyNode = object["specialty"];
  166. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  167. {
  168. const JsonNode & base = specialtyNode["base"];
  169. if(!base.isNull())
  170. {
  171. if(specialtyNode["bonuses"].isNull())
  172. {
  173. logMod->warn("specialty has base without bonuses");
  174. }
  175. else
  176. {
  177. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  178. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  179. JsonUtils::inherit(bonuses[keyValue.first], base);
  180. }
  181. }
  182. }
  183. }
  184. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node) const
  185. {
  186. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  187. {
  188. bonus->duration = BonusDuration::PERMANENT;
  189. bonus->source = BonusSource::HERO_SPECIAL;
  190. bonus->sid = BonusSourceID(hero->getId());
  191. return bonus;
  192. };
  193. //new format, using bonus system
  194. const JsonNode & specialtyNode = node["specialty"];
  195. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  196. {
  197. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  198. return;
  199. }
  200. //creature specialty - alias for simplicity
  201. if(!specialtyNode["creature"].isNull())
  202. {
  203. LIBRARY->identifiers()->requestIdentifier("creature", specialtyNode["creature"], [this, hero, prepSpec](si32 creature)
  204. {
  205. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature)))
  206. hero->specialty.push_back(prepSpec(bonus));
  207. });
  208. }
  209. //secondary skill specialty - alias for simplicity
  210. if(!specialtyNode["secondary"].isNull())
  211. {
  212. LIBRARY->identifiers()->requestIdentifier("secondarySkill", specialtyNode["secondary"], [this, hero, prepSpec](si32 creature)
  213. {
  214. for (const auto & bonus : createSecondarySkillSpecialty(SecondarySkill(creature)))
  215. hero->specialty.push_back(prepSpec(bonus));
  216. });
  217. }
  218. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  219. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  220. }
  221. void CHeroHandler::loadExperience()
  222. {
  223. expPerLevel.push_back(0);
  224. expPerLevel.push_back(1000);
  225. expPerLevel.push_back(2000);
  226. expPerLevel.push_back(3200);
  227. expPerLevel.push_back(4600);
  228. expPerLevel.push_back(6200);
  229. expPerLevel.push_back(8000);
  230. expPerLevel.push_back(10000);
  231. expPerLevel.push_back(12200);
  232. expPerLevel.push_back(14700);
  233. expPerLevel.push_back(17500);
  234. expPerLevel.push_back(20600);
  235. expPerLevel.push_back(24320);
  236. expPerLevel.push_back(28784);
  237. expPerLevel.push_back(34140);
  238. for (;;)
  239. {
  240. auto i = expPerLevel.size() - 1;
  241. auto currExp = expPerLevel[i];
  242. auto prevExp = expPerLevel[i-1];
  243. auto prevDiff = currExp - prevExp;
  244. auto nextDiff = prevDiff + prevDiff / 5;
  245. auto maxExp = std::numeric_limits<decltype(currExp)>::max();
  246. if (currExp > maxExp - nextDiff)
  247. break; // overflow point reached
  248. expPerLevel.push_back (currExp + nextDiff);
  249. }
  250. }
  251. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  252. static std::string genRefName(std::string input)
  253. {
  254. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  255. input[0] = std::tolower(input[0]); // to camelCase
  256. return input;
  257. }
  258. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  259. {
  260. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_HERO);
  261. objects.resize(dataSize);
  262. std::vector<JsonNode> h3Data;
  263. h3Data.reserve(dataSize);
  264. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  265. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  266. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  267. parser.endLine(); //ignore header
  268. parser.endLine();
  269. specParser.endLine(); //ignore header
  270. specParser.endLine();
  271. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  272. {
  273. JsonNode heroData;
  274. heroData["texts"]["name"].String() = parser.readString();
  275. heroData["texts"]["biography"].String() = bioParser.readString();
  276. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  277. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  278. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  279. for(int x=0;x<3;x++)
  280. {
  281. JsonNode armySlot;
  282. armySlot["min"].Float() = parser.readNumber();
  283. armySlot["max"].Float() = parser.readNumber();
  284. armySlot["creature"].String() = genRefName(parser.readString());
  285. heroData["army"].Vector().push_back(armySlot);
  286. }
  287. parser.endLine();
  288. specParser.endLine();
  289. bioParser.endLine();
  290. h3Data.push_back(heroData);
  291. }
  292. return h3Data;
  293. }
  294. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  295. {
  296. size_t index = objects.size();
  297. static const int specialFramesCount = 2; // reserved for 2 special frames
  298. auto object = loadFromJson(scope, data, name, index);
  299. object->imageIndex = static_cast<si32>(index) + specialFramesCount;
  300. objects.emplace_back(object);
  301. registerObject(scope, "hero", name, object->getIndex());
  302. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  303. registerObject(scope, "hero", compatID.String(), object->getIndex());
  304. }
  305. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  306. {
  307. auto object = loadFromJson(scope, data, name, index);
  308. object->imageIndex = static_cast<si32>(index);
  309. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  310. objects[index] = object;
  311. registerObject(scope, "hero", name, object->getIndex());
  312. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  313. registerObject(scope, "hero", compatID.String(), object->getIndex());
  314. }
  315. ui32 CHeroHandler::level (TExpType experience) const
  316. {
  317. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  318. }
  319. TExpType CHeroHandler::reqExp (ui32 level) const
  320. {
  321. if(!level)
  322. return 0;
  323. if (level <= expPerLevel.size())
  324. {
  325. return expPerLevel[level-1];
  326. }
  327. else
  328. {
  329. logGlobal->warn("A hero has reached unsupported amount of experience");
  330. return expPerLevel[expPerLevel.size()-1];
  331. }
  332. }
  333. ui32 CHeroHandler::maxSupportedLevel() const
  334. {
  335. return expPerLevel.size();
  336. }
  337. std::set<HeroTypeID> CHeroHandler::getDefaultAllowed() const
  338. {
  339. std::set<HeroTypeID> result;
  340. for(auto & hero : objects)
  341. if (hero && !hero->special)
  342. result.insert(hero->getId());
  343. return result;
  344. }
  345. VCMI_LIB_NAMESPACE_END